开发者

ASP.NET MVC - Modelbinding with Dropdownlist

开发者 https://www.devze.com 2023-01-24 20:12 出处:网络
Is it possible to have a single view model with a list that is used for a d开发者_JAVA技巧ropdownlist and also get the selected value of the dropdownlist from the view model when I post a form?

Is it possible to have a single view model with a list that is used for a d开发者_JAVA技巧ropdownlist and also get the selected value of the dropdownlist from the view model when I post a form?

If so, how can I do this?


Sure, as always start by defining your view model:

public class MyViewModel
{
    public int? SelectedItemValue { get; set; }
    public IEnumerable<Item> Items { get; set; }
}

public class Item
{
    public int? Value { get; set; }
    public string Text { get; set; }
}

then the controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            // TODO: Fill the view model with data from
            // a repository
            Items = Enumerable
                .Range(1, 5)
                .Select(i => new Item 
                { 
                    Value = i, 
                    Text = "item " + i 
                })
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // TODO: based on the value of model.SelectedItemValue 
        // you could perform some action here
        return RedirectToAction("Index");
    }
}

and finally the strongly typed view:

<% using (Html.BeginForm()) { %>
    <%= Html.DropDownListFor(
        x => x.SelectedItemValue, 
        new SelectList(Model.Items, "Value", "Text")
    ) %>
    <input type="submit" value="OK" />
<% } %>
0

精彩评论

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