繁体   English   中英

模型绑定不适用于int数组

[英]Model binding not working for an array of int

这看起来非常简单,我确信我在过去没有遇到任何问题,但我有一个模型,其中包含一个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);
}

剃刀视图

@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数组为空:

空int数组

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

额外的信息

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

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

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

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

暂无
暂无

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

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