开发者

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" />
<% } %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜