【发布时间】:2016-11-29 14:59:36
【问题描述】:
是否可以启用模型绑定以及表单中的已发布数据?
我有一个集合属性,我想在 foreach 循环中进行迭代以保存集合中的每个选定项:
<div class="form-group">
@Html.LabelFor(m => m.Users, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@{
List<ApplicationUser> allUsers = ViewBag.AllUsers;
bool assigned;
}
<div>
@foreach (var user in allUsers)
{
//here I want to render all users, and only the users who are in the task, have a checked checkbox
assigned = Model.Users.Select(u => u.Id).Contains(user.Id);
<input type="checkbox" name="asndUsers" value="@user.Id" id="@user.Id" @Html.Raw(assigned ? "checked" : "") /> <label style="font-weight: normal;" for="@user.Id">@user.UserName</label><br />
}
</div>
</div>
</div>
//fields updated with model binding:
<div class="form-group">
@Html.LabelFor(m => m.Status, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(m => m.Status, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.Status)
</div>
</div>
这是 Edit action post 方法:
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,Description,DueDate,Status")] UserTask task, string[] asndUsers)
{
if (ModelState.IsValid)
{
task.Users = new List<ApplicationUser>();
foreach (var item in asndUsers)
{
var user = context.Users.Find(item);
task.Users.Add(user);
}
context.Entry(task).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
return View(task);
}
当我调试时它可以工作,我看到新发布的数据已与绑定数据合并。 但是当请求重定向到Index视图时,编辑一个项目后没有变化,这是Index操作方法:
public ActionResult Index(int? taskId)
{
var viewModel = new TasksUsers();
viewModel.Tasks = context.Tasks.Include(x => x.Users);
if (taskId != null)
{
viewModel.Users = viewModel.Tasks.Where(t => t.Id == taskId).Single().Users;
ViewBag.Row = taskId;
}
return View(viewModel);
}
【问题讨论】: