有幾種方法,但存在的方法,它允許你不重複的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"/>
}
ü給了一個非常真棒的答案,兄弟!我要去+++你的答案。有一個有趣的人! –