简体   繁体   English

如何绑定复杂对象列表以在mvc中查看帖子上的模型?

[英]How to bind a list of complex objects to view model on post in mvc?

I am creating x numbers of dropdownlist on the view and want to bind the selected value back to the view model on post. 我在视图上创建x个下拉列表,并希望将所选值绑定回post上的视图模型。 I have seen Scott's post and tried to write my code but still can't get it to work. 我看过斯科特的帖子并尝试编写我的代码,但仍无法使其工作。

My view model consists of two items. 我的视图模型包含两个项目。 One is for the name label for dropdownlist and one is for selected value. 一个用于下拉列表的名称标签,一个用于选定的值。 I need the selected value because I need to pre-select the dropdownlist. 我需要选择的值,因为我需要预先选择下拉列表。

VM VM

public class ColumnMapperVm
{
    public string Column { get; set; }
    public string SelectedValue { get; set; }
}

The view take a list of view model. 该视图采用视图模型列表。 The reason is because i don't know the number of dropdownlist that i need to have on the design time. 原因是因为我不知道设计时需要的下拉列表数量。 It varies to users. 它因用户而异。

@model List<ColumnMapperVm>

@for (int i = 0; i < Model.Count; i++ )
{
    <tr>
        <td style="width: 50%;">
            @Html.DisplayFor(m => m[i].Column)               
        </td>
        <td>
            @Html.DropDownList("SelectedValue", new SelectList(ViewBag.Columns, "StaticName", "DisplayName", Model[i].SelectedValue))
        </td>
    </tr>
}

I put the selectlist in a viewbag coz i want to keep my view model clern and i don't select list won't get posted back to the server. 我把选择列表放在一个viewbag中因为我想保留我的视图模型clern而我不选择列表不会被发回服务器。

And here is my controller 这是我的控制器

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult MapColumns(List<ColumnMapperVm> colmapper)
    {
          //colmapper is null
    }

Of course, I got the values in FormCollection but model binder isn't binding the view model and I wonder how to make it work. 当然,我在FormCollection中获取了值,但模型绑定器没有绑定视图模型,我想知道如何使它工作。

One probable cause might be the fact that currently all dropdowns on post add values with the same name to the request. 一个可能的原因可能是,当前所有下载后添加值都与请求具有相同的名称。 To work this around you can use DropDownListFor : 要解决这个问题,可以使用DropDownListFor

@Html.DropDownListFor(m => m[i].SelectedValue, new SelectList(ViewBag.Columns, "StaticName", "DisplayName"))

This should ensure all dropdowns have correct name in HTML markup. 这应确保所有下拉列表在HTML标记中具有正确的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM