asp.net 将带有视图模型的表单发布到控制器操作方法
-
21-12-2019 - |
题
我有一个相当复杂的表单,需要将其发布到我的 MVC 控制器。
这是我最初在创建时传递给视图的视图模型:
public class EditViewModel
{
public Service service { get; set; }
public bool sms { get; set; }
public bool email { get; set; }
public string userId { get; set; }
}
这是我的观点(简化):
@model IList<Service_Monitor_Web_Interface.Models.ViewModels.EditViewModel>
@{
ViewBag.Title = "Configure User Notifications";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("Edit", "Users", FormMethod.Post, new { @class = "stdform stdform2", role = "form" }))
{
@Html.AntiForgeryToken()
<hr />
<p>
<label><u> Service:</u> </label>
<span class="field">
<u>Notification Methods:</u>
</span>
</p>
for (int i = 0; i < Model.Count; i++)
{
<p>
<label>@Model[i].service.Name</label>
<span class="field">
@Html.CheckBoxFor(model => model[i].sms)
SMS
@Html.CheckBoxFor(model => model[i].email)
Email
</span>
</p>
}
<br clear="all" /><br />
<p class="stdformbutton">
<button class="submit radius2">Save</button>
<input type="reset" class="reset radius2" value="Reset Form" />
</p>
}
这是我的控制器中的 Action 方法:
//
// POST: /Users/Edit
[HttpPost]
public ActionResult Edit(IList<EditViewModel> viewModel)
{
return View(viewModel);
}
在控制器上接收视图模型时如何绑定它?目前,当我调试操作方法时,会收到一个 ViewModel,如下所示:
如何让 service 和 userId 不为空?
解决方案
请注意,在助手的 lambda 中,说 model => service.sms
右边部分(service.sms
) 形式上不是从左边部分 (model
)。这导致所有 name
结果输入的属性相同,并为您提供您不期望的请求参数。
标准做法是使用 for
代替 foreach
在循环情况下。这样,结果 html 的名称属性就可以正确生成:
for(int i=0; i<Model.Count; i++)
{
<p>
<label>@Model[i].service.Name</label>
<span class="field">
@Html.CheckBoxFor(model => model[i].sms)
SMS
@Html.CheckBoxFor(model => model[i].email)
Email
</span>
</p>
}
请注意,这需要 Model
属于实施类型 IList
而不是 IEnumerable
.
更新。 对于没有任何 UI 的其他值,您可以使用隐藏字段,以便它们对用户不可见,但仍会发布到服务器:
<label>@Model[i].service.Name</label>
<span class="field">
@Html.CheckBoxFor(model => model[i].sms)
SMS
@Html.CheckBoxFor(model => model[i].email)
Email
@Html.HiddenFor(mode => model[i].userId)
@Html.HiddenFor(mode => model[i].service.Name)
...other field of service you want to be posted...
</span>
不隶属于 StackOverflow