有几种方法,但存在允许您不重复 UI 字段并具有单个提交按钮的方法,您可以根据所选用户 AccountType 划分模型验证,自定义 ActionMethodSelectorAttribute 帮助您根据用户帐户类型划分方法。模型将在适当的行动中自动验证。
这是示例实现:
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new SignUpModel
{
Common = new Common(),
Personal = new Personal(),
Company = new Company()
});
}
[HttpPost]
[SignUpSelector]
[ActionName("Index")]
public ActionResult PersonalRegistration(Personal personal, Common common)
{
if (ModelState.IsValid)
{
//your code
}
return View("Index", new SignUpModel()
{
Common = common,
Personal = personal,
Company = new Company()
});
}
[HttpPost]
[SignUpSelector]
[ActionName("Index")]
public ActionResult CompanyRegistration(Company company, Common common)
{
if(ModelState.IsValid)
{
//your code
}
return View("Index", new SignUpModel()
{
Common = common,
Personal = new Personal(),
Company = company
});
}
}
模型:
public class SignUpModel
{
public string AccountType { get; set; }
public Common Common { get; set; }
public Company Company { get; set; }
public Personal Personal { get; set; }
}
public class Company
{
[Required]
public string CompanyName { get; set; }
public string Address { get; set; }
}
public class Personal
{
[Required]
public string FirstName { get; set; }
public int Age { get; set; }
}
public class Common
{
[Required]
public string UserName { get; set; }
[Required]
public string Passwrod { get; set; }
}
自定义 ActionMethodSelectorAttribute:
public class SignUpSelector : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
return (controllerContext.HttpContext.Request.Form["AccountType"] + "Registration" == methodInfo.Name);
}
}
看法:
@model MvcModelValidationTest.Controllers.SignUpModel
@{
ViewBag.Title = "Home Page";
}
@using(Html.BeginForm())
{
@Html.Display("Personal")
@Html.RadioButtonFor(x=>x.AccountType, "Personal",new { @checked = "checked" })<br/>
@Html.Display("Company")
@Html.RadioButtonFor(x=>x.AccountType, "Company")<br/>
@Html.TextBoxFor(x=>x.Common.UserName)<br/>
@Html.PasswordFor(x=>x.Common.Passwrod)<br/>
@Html.TextBoxFor(x=>x.Company.CompanyName)<br/>
@Html.TextBoxFor(x=>x.Company.Address)<br/>
@Html.TextBoxFor(x=>x.Personal.FirstName)<br/>
@Html.TextBoxFor(x=>x.Personal.Age)<br/>
<input type="submit"/>
}