模型绑定不适用于int数组

时间:2016-01-15 00:31:20

标签: c# asp.net-mvc

这看起来非常简单,我确信我在过去没有遇到任何问题,但我有一个模型,其中包含一个int数组:

查看模型

public class ExampleViewModel
{
    public int ExampleProperty1 { get; set; }
    public int[] ExampleProperty2 = {};
    public string ExampleProperty3 { get; set; }
}

现在,我将使用一些数据预加载此视图模型并显示一个表单:

控制器操作

public ViewResult Example1()
{
    var viewModel = new ExampleViewModel
    {
        ExampleProperty1 = 888,
        ExampleProperty2 = new [] { 1, 2, 3, 4 },
        ExampleProperty3 = "Test string"
    };
    return View(viewModel);
}

Razor视图

@using (Html.BeginForm("example2", "class", FormMethod.Post, new {id = "ExampleForm"}))
{
    @Html.HiddenForEnumerable(m => m.ExampleProperty2)
    @Html.TextBoxFor(m => m.ExampleProperty1)
    @Html.TextBoxFor(m => m.ExampleProperty3)

    <input type="submit"/>
}

“HiddenForEnumerable”扩展方法如下所示:

public static MvcHtmlString HiddenForEnumerable<TModel, TProperty>(this HtmlHelper<TModel> helper,
        Expression<Func<TModel, IEnumerable<TProperty>>> expression)
{
    var sb = new StringBuilder();

    var membername = expression.GetMemberName();
    var model = helper.ViewData.Model;
    var list = expression.Compile()(model).ToList();

    for (var i = 0; i < list.Count(); i++)
    {
        sb.Append(helper.Hidden(string.Format("{0}[{1}]", membername, i), list.ElementAt(i)));
    }

    return new MvcHtmlString(sb.ToString());
}

并生成以下HTML:

<input id="ExampleProperty2_0_" name="ExampleProperty2[0]" type="hidden" value="1">
<input id="ExampleProperty2_1_" name="ExampleProperty2[1]" type="hidden" value="2">
<input id="ExampleProperty2_2_" name="ExampleProperty2[2]" type="hidden" value="3">
<input id="ExampleProperty2_3_" name="ExampleProperty2[3]" type="hidden" value="4">

到目前为止,这么好。但是,当我将表单提交给此操作时:

public ViewResult Example2(ExampleViewModel viewModel)
{
    return View();
}

int数组为空:

Empty int array

所以问题是:如何让MVC正确检测int数组并将其分配给视图模型?

额外信息

如果它很重要,这就是POST请求正文的样子:

ExampleProperty2%5B0%5D=1&ExampleProperty2%5B1%5D=2&ExampleProperty2%5B2%5D=3&ExampleProperty2%5B3%5D=4&ExampleProperty1=888&ExampleProperty3=Test+string

1 个答案:

答案 0 :(得分:5)

您需要将ExampleProperty2设为属性(使用getter / setter),以便DefaultModelBinder可以设置属性的值

public class ExampleViewModel
{
  public int ExampleProperty1 { get; set; }
  public int[] ExampleProperty2 { get; set; } // change this
  public string ExampleProperty3 { get; set; }
}