How does Model binding with a selectlist work?
I'm having problems retrieving the values of a selectlist in my form collection. I've tried making a viewmodel with an 开发者_开发知识库attribute with the same name as the select list.
I'm honestly just realizing I REALLY don't understand how model binding works with selectlists. I've just been assuming that the following conventions apply:
- Name the select list the same thing as the attribute on the model you want it to bind to.
Apart from that, I really don't get it. I've looked at several books on it and they're useless frankly.
How does a select list work with a) form collection and b) a particular model?
Here's an example:
Model:
public class MyViewModel
{
    public string SelectedItemValue { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}
Controller:
public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            // TODO: Fetch those from a repository
            Items = new SelectList(
                new[]
                {
                    new SelectListItem { Value = "1", Text = "Item 1" },
                    new SelectListItem { Value = "2", Text = "Item 2" },
                    new SelectListItem { Value = "3", Text = "Item 3" },
                }, 
                "Value", 
                "Text"
            )
        };
    }
    [HttpPost]
    public ActionResult Index(string selectedItemValue)
    {
        // Here you get the selected value from the dropdown
        return ...
    }
}
View:
<% using (Html.BeginForm()) { %>
    <%= Html.DropDownListFor(x => x.SelectedItemValue, Model.Items)
    <input type="submit" value="OK" />
<% } %>
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论