目标:
使用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; }
}
答案 0 :(得分:0)
而不是ModelState您可以使用ViewBag或ViewData删除重复。
public ActionResult Add(AddUserVM model)
{
model = Test1(model);
if(!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult Add_dd(AddUserVM model)
{
Test1(model);
if(!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Index");
}
private void Test1(AddUserVM model)
{
if(model.FirstName == model.LastName)
{
ViewBag.ErrorMessage ="The last name cannot be the same as the first name.";
}
}