如何将List <t>从View传递给Controller?</t>

时间:2014-06-18 15:23:23

标签: asp.net-mvc razor

如果我的模型具有属性List<MyType> MyProperty(其中MyType是复杂类型),我该如何将其传递给Controller Action?

e.g。

[HttpGet]
public ActionResult UpdateAll(List<MyType> thingy)

如果我只是使用

Model.MyProperty

它在控制器中显示为null

我无法绕过我能找到的例子 - 但我可以接受的是让我认为我应该说我的观点不是基于IEnumerable<MyType>(也不应该/应该)它是。)

编辑:我想用它做什么

 <a id="updateall" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" href="@Url.Action("UpdateAll", "MyController", new { area = "Operator", myproperty=Model.MyProperty})"><span class="ui-button-text">Update All</span></a>

EDIT2:它是否像我需要在传递它之前序列化一样简单?但我认为很快就会出现一个答案/搜索结果......

2 个答案:

答案 0 :(得分:2)

在MVC中列表的处理方式略有不同,为了从列表中发回数据,您需要首先为该列表中的每个项目呈现UI,即

@model MyComplexModel

@foreach (MyType item in Model.MyProperty)
{
    @Html.EditorFor(x => item.SomeProperty)
    @Html.EditorFor(x => item.AnotherProperty)
}

使用*For帮助程序将生成相应的HTML,允许模型绑定器知道它正在更新的列表中的哪些项目。如果您检查DOM,您应该会发现列表项的HTML类似于

<input type="text" name="Model.MyProperty[0].SomeProperty" />
<input type="text" name="Model.MyProperty[0].AnotherProperty" />
<input type="text" name="Model.MyProperty[1].SomeProperty" />
<input type="text" name="Model.MyProperty[1].AnotherProperty" />
...

答案 1 :(得分:0)

我在javascript对象中有我的View中的数据。如果这是你要去的方向......

我有一个toDictionary方法......

(function ($) {
    $.extend({
        toDictionary: function (data, prefix, includeNulls) {
            /// <summary>Flattens an arbitrary JSON object to a dictionary that Asp.net MVC default model binder understands.</summary>
            /// <param name="data" type="Object">Can either be a JSON object or a function that returns one.</data>
            /// <param name="prefix" type="String" Optional="true">Provide this parameter when you want the output names to be prefixed by something (ie. when flattening simple values).</param>
            /// <param name="includeNulls" type="Boolean" Optional="true">Set this to 'true' when you want null valued properties to be included in result (default is 'false').</param>

            // get data first if provided parameter is a function
            data = $.isFunction(data) ? data.call() : data;

            // is second argument "prefix" or "includeNulls"
            if (arguments.length === 2 && typeof (prefix) === "boolean") {
                includeNulls = prefix;
                prefix = "";
            }

            // set "includeNulls" default
            includeNulls = typeof (includeNulls) === "boolean" ? includeNulls : false;
            var result = [];
            _flatten(data, result, prefix || "", includeNulls);

            return result;
        }
    });
}

以下是我的ajax调用,其中roles是javascript Object()

var data = { roleGroups: roles };
$.ajax({
    url: '/Controller/Action',
    type: 'post',
    dataType: 'json',
    data: $.toDictionary(data)
})

然后我在服务器上使用了IList ...

[HttpPost]
public virtual ActionResult EditRoleGroups(IList<RoleGroupViewModel> roleGroups)
{ 
    //do stuff
}
相关问题