是否可以将单个视图模型带有用于下拉列表的列表,并且在我发布表单时也从视图模型中获取订单列表的选定值?

如果是这样,我该怎么做?

有帮助吗?

解决方案

当然,一如既往地从定义您的视图模型开始:

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; }
}

然后控制器:

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");
    }
}

最后是强烈键入的观点:

<% 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