【发布时间】:2017-05-13 06:02:03
【问题描述】:
在视图中有一个 for 循环,它生成 4 个表单,只有一个提交按钮,当单击该按钮时,表单中的每个条目都会被发布。
在我的 HttpPost 控制器中,我执行了以下操作:
[HttpPost]
public ActionResult Index(List<ForTestingOnly> receivedData)
{
receivedData.ForEach(delegate (ForTestingOnly data)
{
get_Description += data.Description + ", ";
get_Name += data.Name + ", ";
});
ViewData["P_Description"] = get_Description;
ViewData["P_Name"] = get_Name;
return View();
}
我收到以下错误:
用户代码未处理 NullReferenceException MVC_Application.dll 中出现“System.NullReferenceException”类型的异常,但未在用户代码中处理。 附加信息:对象引用未设置为对象的实例。
我尝试了另一种方法:
[HttpPost]
public ActionResult Index(List<ForTestingOnly> receivedData)
{
foreach (ForTestingOnly data in receivedData)
{
get_Description += data.Description + ", ";
get_Name += data.Name + ", ";
}
ViewData["P_Description"] = get_Description;
ViewData["P_Name"] = get_Name;
return View();
}
我再次收到以下错误:
用户代码未处理 NullReferenceException MVC_Application.dll 中出现“System.NullReferenceException”类型的异常,但未在用户代码中处理。 附加信息:对象引用未设置为对象的实例。
之后我在 HttpPost 控制器中添加了以下内容:
receivedData = new List<ForTestingOnly>();
添加上面的代码后,错误信息消失了。但是,当我在单击提交按钮后尝试在视图的文本框中显示输入的数据时,什么都没有出现。
下面是模型和视图:
型号:
public class ForTestingOnly
{
[Display(Name = "Description: ")]
[Required(ErrorMessage = "The description of the sub event is required.")]
public string Description { get; set; }
[Display(Name = "Name: ")]
[Required(ErrorMessage = "The name is required.")]
public string Name { get; set; }
}
查看:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<h4>Count: @ViewData["Count"]</h4>
<br />
<h4>Posted Description: @ViewData["P_Description"]</h4>
<br />
<h4>Posted Name: @ViewData["P_Name"]</h4>
<br />
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@for(int counter = 0; counter<2; counter++) {
<h5>Form: @(counter + 1)</h5>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
【问题讨论】:
-
您的视图正在为单个
ForTestingOnly创建表单控件,而不是集合。您需要在 GET 方法中初始化一个新的List<ForTestingOnly>,用 2 个项目填充它并将其返回到视图,然后使用for循环或EditorTemplate正确生成表单控件(请参阅 this answer. -
@StephenMuecke 请给我推荐另一个例子。
标签: c# asp.net-mvc razor view controller