문제

Is it possible to have a single view model with a list that is used for a dropdownlist 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" />
<% } %>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top