gpt4 book ai didi

c# - 模型绑定(bind)不适用于 int 数组

转载 作者:行者123 更新时间:2023-11-30 14:51:17 25 4
gpt4 key购买 nike

这看起来很简单,我敢肯定我过去做过没有问题,但我有一个模型,其中包含一个 int 数组:

查看模型

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

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

Controller 操作

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

Razor View

@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 数组并将其分配给 View 模型?

额外信息

如果它很重要,这就是 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; }
}

关于c# - 模型绑定(bind)不适用于 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34802380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com