in my very first asp.net mvc4 project,i'm trying to apply some validation tests on my four forms in the same page.Each form allows me to create a different type of project in my table(dataBase),so i'm using the same model generated by entity framework and for validation i used a partial class having the same name of my generated model and i've inserted data annotation such as required with error messages.My problem is when i submit one form leaving a required field empty,the appropriate validation error message is shown for all my forms and not only the one i submitted.Please can someone tell me how can i solve this problem?
2 Answers
If you have a RequiredAttribute on (say) property Name and its null on postback, a validation error is added for that property. If you inspect the html generated for the form, you will see something like this (assuming your using @Html.ValidationMessageFor(m => m.Name)) which acts as a placeholder for any validation error message associated with Name
<span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
Note the ..data-valmsg-for="Name"... Since your rendering 4 identical forms using the same model which generates 4 inputs for property Name, there will be 4 corresponding validation errors.
Your approach in rendering 4 identical forms does not make sense since you can only post one back. I suggest you consider using a view model that includes a property for ProjectType and render a DropDownList so the user can select the project type. Then only one form is required, and when submitting, get the selected ProjectType and use this to make whatever decisions you need to save the data.
5 Comments
public ProjectType1 Project1 { get; set; } etc, then render the inputs as @Html.TextBoxFor(m => m.Project1.Name), @Html.TextBoxFor(m => m.Project2.Name) etc so the the controls have distinct names and distinct associated validation controls.Just structure your View in this way :-
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { @Id = "Form1" }))
{
..........
..........
<button type="submit">Update this stuff</button>
}
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { @Id = "Form2" }))
{
..........
..........
<button type="submit">Update this stuff</button>
}
In above example when you submit "Form1" model validations associated with "Form1" will fire and same case for "Form2".