【发布时间】:2016-03-03 11:47:31
【问题描述】:
目标:
使用 HTTP 减少与 Actionresult 相关的代码重复。
问题:
我有两个带有 Actionresult(带有 HTTP)的 actionresult,它们具有相同的源代码,是重复的代码。
我应该如何启用代码“ModelState.AddmodelError”用于 在这种情况下,这两个操作都没有重复代码?
信息:
*请记住此代码是大项目的一个简单示例。
*我正在使用 asp.net mvc 4
*今天我重构了一个源代码,以减少重复的代码。
*有两个不同动作的原因说来话长,但现在我正在重构
今天的源码:
[HttpPost]
public ActionResult Add(AddUserVM model)
{
if(model.FirstName == model.LastName)
{
ModelState.AddModelError("LastName", "The last name cannot be the same as the first name.");
}
if(!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Add_dd(AddUserVM model)
{
if(model.FirstName == model.LastName)
{
ModelState.AddModelError("LastName", "The last name cannot be the same as the first name.");
}
if(!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Index");
}
Proposal that is might not working:
public ActionResult Add(AddUserVM model)
{
model = Test1(model);
if(!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Add_dd(AddUserVM model)
{
model = Test1(model);
if(!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Index");
}
private model Test1(AddUserVM model)
{
if(model.FirstName == model.LastName)
{
ModelState.AddModelError("LastName", "The last name cannot be the same as the first name.");
}
return ""
}
public class AddUserVM
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
}
【问题讨论】:
-
使用 foolproof
[NotEqualTo]或类似的验证属性,以便您获得客户端和服务器端验证
标签: asp.net-mvc-4 actionresult modelstate