asp.net-mvc 带有实体框架的MVC下拉列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26663068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:18:32  来源:igfitidea点击:

MVC Drop Down list with entity framework

asp.net-mvcentity-frameworkmodel-view-controller

提问by dc922

I've created an MVC project using entity framework code first. My model is simply a form that gathers information.

我首先使用实体​​框架代码创建了一个 MVC 项目。我的模型只是一个收集信息的表格。

public class Application
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleInitial { get; set; }
    public string LastName { get; set; }
    public int SSN { get; set; }
    public DateTime DOB { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string State {get; set; }
    public string Zip { get; set; }
    public int HomePhone { get; set; }
    public int BusinessPhone { get; set; }
    public int MobilePhone { get; set; }

}

}

My goal is to create a drop down list with all of the states, but I'm finding this to be very difficult given that I've already created the database via scaffolding with views and controllers. Is there a simple way to do this and tie it in with the existing database? I've searched for almost the entire day with no luck. An overview/explanation of what to include for the model/controller/view would be amazing!

我的目标是创建一个包含所有状态的下拉列表,但我发现这非常困难,因为我已经通过带有视图和控制器的脚手架创建了数据库。有没有一种简单的方法可以做到这一点并将其与现有数据库联系起来?我几乎一整天都没有找到运气。对模型/控制器/视图包含的内容的概述/解释将是惊人的!



Update: I've created a new model named "State" with properties "Id" and "StateName" and have created some states in the database. In my "Application" controller inside the Create action method I have:

更新:我创建了一个名为“State”的新模型,其属性为“Id”和“StateName”,并在数据库中创建了一些状态。在我的 Create action 方法内的“应用程序”控制器中,我有:

Controller

控制器

public ActionResult Create()
    {

        ApplicationDbContext db = new ApplicationDbContext();
        this.ViewData["Id"] = new SelectList(db.States.ToList(), "Id", "StateName");
        return View();
    }

View

看法

@Html.DropDownList("Id")

Now the problem is I'm getting this error " There is no ViewData item of type 'IEnumerable' that has the key 'Id'." Would really appreciate help!

现在的问题是我收到此错误“没有具有键 'Id' 的 'IEnumerable' 类型的 ViewData 项。” 非常感谢帮助!

回答by AbdulG

Its quite simple. Add an IEnumerable<SelectListItem>property to your model(Here I suggest you make a ViewModel that can have the exact same properties as Applicationwith the below code included as a property). Then you just need to build the list and send it to your view

它很简单。IEnumerable<SelectListItem>为您的模型添加一个属性(在这里我建议您制作一个 ViewModel,它可以具有Application与作为属性包含的以下代码完全相同的属性)。然后您只需要构建列表并将其发送到您的视图

public IEnumerable<SelectListItem> States{ get; set; }

I will assume you want to retrieve the Statevalues from the db. Here is how you will do it:

我假设您想State从数据库中检索值。以下是您的操作方法:

private IEnumerable<SelectListItem> GetAllStates()
{
    IEnumerable<SelectListItem> list = from s in db.Applications
                                       select new SelectListItem
                                       {
                                           Selected = false,
                                           Text = s.State,
                                           Value = s.State
                                       };
    return list;
}

Or this...

或这个...

private IEnumerable<SelectListItem> GetAllStates()
{
    IEnumerable<SelectListItem> list = db.Applications.Select(s => new SelectListItem
                                       {
                                           Selected = false,
                                           Text = s.State,
                                           Value = s.State
                                       });

    return list;
}

Then do something like this in your action:

然后在你的行动中做这样的事情:

var app = new Application
{
    States = GetAllStates()
};

return View(app);

Then finally, use Razor on the view to display the Dropdown list like this

最后,在视图上使用 Razor 来显示这样的下拉列表

@Html.DropDownListFor(m => m.State, Model.States, "--Select a State--")

The 1st parameter is the property of the model to update, the 2nd is the list of data, and 3rd is the default message that will be displayed

第一个参数是要更新的模型的属性,第二个是数据列表,第三个是将显示的默认消息

Hope this helps.

希望这可以帮助。

回答by John Peters

Create a data layer that retrieves a list of what you want. Then use EF to get all the states.

创建一个数据层来检索您想要的列表。然后使用EF获取所有状态。

//assuming you have a table of states..
var states = db.States();

The states table should be a Unique list of states.

状态表应该是一个唯一的状态列表。

var selectList = new List<SelectListItem>(); 
foreach(var thing in states){
    //if you got everything, thus the ID field for the value...   
   selectList.Add(new SelectListItem {Text =thing.State, Selected = false, Value = thing.ID);
}

Make sure in your Viewmodel class that selectlist is a public property.....and set to what you did above. You also need to provied a string for the view selection post back.

确保在您的 Viewmodel 类中,选择列表是一个公共属性.....并设置为您在上面所做的。您还需要为视图选择回发提供一个字符串。

StatesSelectList = selectList;
public IEnumberable<SelectListItem> StatesSelectList {get;set;}
public string SelectedState {get;set;}

In your view, do this:

在您看来,请执行以下操作:

@Html.DropDownListFor(p=>Model.SelectedState, Model.StatesSelectList)

回答by Saif

Very simple Code step by step

非常简单的代码一步一步

1) In Entity Framework Class

1) 在实体框架类中

var productsList = (from product in dbContext.Products
                     select new ProductDTO
                     {
                       ProductId = product.ProductId,
                       ProductName = product.ProductName,
                       }).ToList();

2) In Controller

2) 在控制器中

ViewBag.productsList = new EntityFrameWorkClass().GetBusinessSubCategoriesListForDD();

3) In View

3) 在视图中

@Html.DropDownList("Product_ProductId", new SelectList(ViewBag.productsList, "ProductId", "ProductName"), new { @class = "form-control" })

OR

或者

@Html.DropDownListFor(m=>m.Product_ProductId, new SelectList(ViewBag.productsList , "ProductId", "ProductName"), new { @class = "form-control" })

回答by Matt Watson

I assume there is a States model that has a Id and a StateName property.

我假设有一个具有 Id 和 StateName 属性的状态模型。

Change to the list to ViewData["State"] to ensure easy binding on POST.

将列表更改为 ViewData["State"] 以确保在 POST 上轻松绑定。

Id is the value that will be sent in the POST data ie.. State = Id. The StateName is what will be displayed in the Select list. So for your model this is not correct as State is a string.So needs to be

Id 是将在 POST 数据中发送的值,即.. State = Id。StateName 是将显示在选择列表中的内容。 因此,对于您的模型,这是不正确的,因为 State 是一个字符串。所以需要是

this.ViewData["State"] = new SelectList(db.States.ToList(), "StateName", "StateName");

Then in your view

那么在你看来

@Html.DropDownList("State")