- Back to Home »
- Asp.net MVC3 validation independent of Model
Posted by :
Unknown
Saturday, October 15, 2011
I was facing an tricky situation where a page will have multiple inputs derived from one model property. E.g. There is a model which has property called "Question" which will be used in a view where there will be multiple instance of this Question property as a input textbox but only first question should be mandatory and rest questions should be optional.
Now when I add RequiredField attribute in model itself and add @HtmlValidationMessageFor in view it shows validation message for all input fields.
SurveyQuestionsModel.cs
Now when I add RequiredField attribute in model itself and add @HtmlValidationMessageFor in view it shows validation message for all input fields.
SurveyQuestionsModel.cs
@Html.TextBoxFor(model => model.SurveyQuestions[i].Question) @Html.ValidationMessageFor(model => model.SurveyQuestions[i].Question)
SurveyQuestion.cshtml
[Required(ErrorMessage = "Required field")]
[Display(Name = "Question")]
public string Question {get;set;}
Finally I got the solution, though I think it's not the correct way. But it solved my issue. Steps I did to fix the issue -
- I observed Html for input fields for which there is an validation error. The input field will have additional attributes such as "data-val-required" and "data-val"
- Then I added these fields to textbox which needs to be validated.
- Then I added Html.Validation() for textbox with validation message.
My final code in SurveyQuestion.cshtml looks like this
@if (i == 0)
{
@Html.TextBoxFor(model => model.SurveyQuestions[i].Question, new Dictionary { { "data-val-required", "required" }, { "data-val", "true" }, { "title", "Question " + (i + 1) }, {"class","QuestionTextBox"} })
@Html.ValidationMessage("SurveyQuestions[0].Question", "At least one question is required.")
}
else
{
@Html.TextBoxFor(model => model.SurveyQuestions[i].Question, new { @class = "QuestionTextBox", @title = "Question " + (i + 1) })
}