简体   繁体   English

ASP.NET MVC 4 DropdownListFor,使用来自DBContext的LINQ进行填充?

[英]ASP.NET MVC 4 DropdownListFor, Populating using LINQ from DBContext?

Having a hard time finding answer to this question (Google, StackOverflow and ASP.NET). 很难找到该问题的答案(Google,StackOverflow和ASP.NET)。

// Model
public IEnumerable<SelectListItem> State { get; set; }

// View
@Html.DropDownListFor(m => m.State, ????)

// Controller

using (var dbcontext = MyDbContext()) {

    // ??
}

return View(model);

I'm at a complete loss how to populate a mvc dropdownlistfor using LINQ from a DBContext. 我完全不知道如何使用DBContext中的LINQ填充mvc dropdownlist。 I understand the DBContext thing and have one setup. 我了解DBContext,并进行了一项设置。 I'm not clear on how to construct a linq query and then pass that result (LIST?) to the DropDownListFor helper? 我不清楚如何构造linq查询,然后将该结果(LIST?)传递给DropDownListFor helper? Using MS SQL and I have a States table (id, name). 使用MS SQL,我有一个状态表(ID,名称)。

Firstly, in you model, include properties for what you want to bind to and the list of selections 首先,在模型中,包括要绑定的属性和选择列表

public class MyViewModel
{
  public string StateID { get; set; }
  .... // other properties
  public SelectList StateList { get; set; }
}

In the controller 在控制器中

// Initialise view model
MyViewModel model = new MyViewModel();
// Select the data to display (lots of ways to do this)
var states= from s in dbcontext.States
                 where s.SomeProperty == someValue // if you want to filer the results
                 select s
// Assign select list (this sets the value to the ID property and the display text to the Name property)
model.StateList = new SelectList(states, "ID", "Name");
// and if you want to set a default
model.StateID = "NY";
return View(model);

and in the view 并认为

@Html.DropDownListFor(m => m.StateID, Model.StateList)

this will display the full name of the states in the <select> and bind the states ID value to the property StateID 这将在<select>显示状态的全名,并将状态ID值绑定到属性StateID

//dbcontext

using (var dbcontext = MyDbContext()) 
{
Dictionary<string, string> states = dbcontext .States.ToDictionary(t => t.StateID.ToString(), t => t.StateName.ToString());

}

// in controller attach this dictionary to ViewBag:

ViewBag.States=states;

// View //查看

 @Html.DropDownListFor(m => m.State,  new SelectList(ViewBag.States, "Key", "Value"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM