Reputation: 450
I have multiple @Html.BeginForm
's in my strongly-type View, which inherits from one Model. Some of the fields in the Model are [Required]
and some are not. When the second @Html.BeginForm
is submitted, it did not include some of the [Required] Html.TextBoxFor
items from the first @Html.BeginForm
. As a result the validation message is showing in the first @Html.BeginForm
block.
It would be nice if each @Html.BeginForm
could inherit from different Models, to produce independent sets of TextBoxFor
and ValidationFor
.
Question: Does anyone know how to suppress the validation in the first form when submitting the second form?
Upvotes: 0
Views: 184
Reputation: 450
I'm trying to avoid conditional logic in my View. I think the validator does not behave as I expected on multiple forms within a page. So I ended up removing the validators and [Required] fields alltogether and added manual validation within the controller that looks like this:
StringBuilder sb = new StringBuilder();
if (mm.field1 == null)
sb.Append("<li>field1 is required</li>");
if (mm.field2 == null)
sb.Append("<li>field2 is required</li>");
// .... and on and on
if (sb.ToString != "")
{
ViewData["validationMessage1"] = "<ul>" + sb.ToString() + "</ul>";
return View("MyView",mm);
}
// Process form below here, at this point all required fields have passed validation
Upvotes: 0
Reputation: 1036
Well, assuming you just have one controller that handle all of your form. first of all you need to check what form is empty like this:
@{
if(!Request["form1"].IsEmpty()){
//sending data form 1...
}
if(!Request["form2"].IsEmpty()){
//sending data form 2
}
if(!Request["form3"].IsEmpty()){
//sending data form 3
}
}
It's best practice to separate the controller or method for each form.
Upvotes: 1