我有一个用于编辑演出的表格。
初始控制器操作称为“编辑”。
表单发布到名为“更新”的第二个控制器操作
因此,一旦表单发布,我使用一个定制的ModelBinder,它使用bindingContext.ModelState.AddModelError将验证消息添加到模型状态
更新copntroller操作如下所示:
[AcceptVerbs("POST")]
public ActionResult Update(Guid id, FormCollection formCollection)
{
Gig gig = GigManager.GetByID(id);
try
{
UpdateModel<Gig>(gig);
GigManager.Save(gig);
return RedirectToAction("List");
}
catch (Exception e)
{
return View(gig);
}
}
如果模型绑定器有错误,更新模型将抛出异常。
这意味着调用RedirectToAction(“Edit”),以便调用原始的“Edit”控制器操作。
这意味着我不会看到我的验证消息,用户添加到表单的任何数据都将重置为原始值!
我该如何接近这个?
我已在下面添加了“编辑”操作:
[AcceptVerbs("GET")]
public ActionResult Edit(Guid id)
{
Gig gig = GigManager.GetByID(id);
SelectList days = CreateDays(1, 31, 1, gig.StartDate.Day);
ViewData["day"] = days;
SelectList months = CreateMonths(1, 12, 1, gig.StartDate.Month);
ViewData["month"] = months;
SelectList years = CreateYears(DateTime.Now.Year, DateTime.Now.Year + 10, 1, gig.StartDate.Year);
ViewData["year"] = years;
string bandNames ="";
string bandIds = "";
foreach(Act act in gig.Acts)
{
bandNames += act.Name.Trim() + ", ";
if (act.Artist != null)
{
bandIds += act.Artist.ID + ";";
}
}
ViewData["Bands"] = bandNames;
ViewData["BandIds"] = bandIds;
return View(gig);
}
但是,我没有得到验证信息
答案 0 :(得分:1)
也许这会有所帮助。我刚刚提交了一个控制器来执行列表/编辑管理员。它在一个可能很方便的类上使用绑定。查看文件的最后一部分,以查看处理Get和Post Verbs的可能方法。请注意,UpdateModelStateWithViolations只是向ModelState添加错误的帮助程序。
Controller.ModelState.AddModelError(violation.PropertyName,
violation.ErrorMessage);
显示为
<%= Html.ValidationSummary() %>
http://www.codeplex.com/unifico/SourceControl/changeset/view/1629#44699
和视图:http://www.codeplex.com/unifico/SourceControl/changeset/view/1629#54418
[AcceptVerbs("GET")] [Authorize(Roles = "Admin")] public ActionResult EditRole(Guid? RoleID) { Role role = null; RoleForm form = new RoleForm { }; if (RoleID.HasValue) { role = accountService.GetRole(RoleID.Value); if (role == null) return RedirectToAction("Roles"); form = new RoleForm { RoleID = role.ID, RoleName = role.Name, Level = role.Level }; } else { form = new RoleForm(); } ViewData.Model = form; return this.PluginView(); } [AcceptVerbs("POST")] [Authorize(Roles = "Admin")] public ActionResult EditRole(Guid? RoleID, [Bind(Include = "RoleID,RoleName,Level", Prefix = "")] RoleForm form) { Role role = null; if (RoleID.HasValue) { role = accountService.GetRole(RoleID.Value); if (role == null) return RedirectToAction("Roles"); } ServiceResponse<Role> response = accountService.AttemptEdit(form); if (response.Successful) { TempData["Message"] = "Update Successfull"; } else { this.UpdateModelStateWithViolations(response.RuleViolations); } //ViewData["AllRoles"] = accountService.GetRolePage(new PageRequest(0, 50, "Name", typeof(string), true)).Page.ToArray(); ViewData.Model = form; return this.PluginView(); }