MVC如何忽略嵌套视图模型的验证 [英] MVC how to ignore validation of nested view model
问题描述
我有一个页面,可以将两个视图模型发布到控制器上,即查询"和约会".约会嵌套在查询中.用户可以选择向我们提交查询而无需创建约会.
I have a page with which i post two view models to the controller, Enquiry and Appointment. Appointment is nested within enquiry. A user can choose to submit an enquiry with our without creating an appointment .
我在视图模型属性上使用了内置的MVC必需属性.
I use the built in MVC required attributes on the view model properties.
我的问题是,当用户选择创建不带约会的查询时,如何优雅地忽略嵌套约会视图模型上的验证器并使ModelState.IsValid返回true?
My question is, when the user chooses to create an enquiry without an appointment, how can I elegantly ignore the validators on the nested Appointment view model and have ModelState.IsValid return true?
if(!viewModel.CreateAppointment)
{
//ignore the nested view models validation
}
推荐答案
您可以创建一个自定义的IgnoreModelError属性,如下所示,并在视图中使用2个单独的按钮,一个仅用于查询,另一个用于约会.
You can make a custom IgnoreModelError attribute as shown below and use 2 separate buttons in your view one for enquiry only and one for appointment.
// C#
public class IgnoreModelErrorAttribute : ActionFilterAttribute
{
private string keysString;
public IgnoreModelErrorsAttribute(string keys)
: base()
{
this.keysString = keys;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ModelStateDictionary modelState = filterContext.Controller.ViewData.ModelState;
string[] keyPatterns = keysString.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < keyPatterns.Length; i++)
{
string keyPattern = keyPatterns[i]
.Trim()
.Replace(@".", @"\.")
.Replace(@"[", @"\[")
.Replace(@"]", @"\]")
.Replace(@"\[\]", @"\[[0-9]+\]")
.Replace(@"*", @"[A-Za-z0-9]+");
IEnumerable<string> matchingKeys = _
modelState.Keys.Where(x => Regex.IsMatch(x, keyPattern));
foreach (string matchingKey in matchingKeys)
modelState[matchingKey].Errors.Clear();
}
}
}
[HttpPost]
[IgnoreModelErrors("Enquiry.Appointment")]
public ActionResult CreateEnquiryOnly(Enquiry enquiry)
{
// Code for enquiry only.
}
[HttpPost]
public ActionResult CreateAppointment(Enquiry enquiry)
{
// Code for appointment.
}
这篇关于MVC如何忽略嵌套视图模型的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!