Reputation: 6270
I have asp.net MVC3 app where validations are done by adding validation attribute in model. e.g.
[Required(ErrorMessage = "Required field")]
[Display(Name = "SurveyName")]
[DataType(DataType.Text)]
public string SurveyName {get;set;}
Then I create text box in view
@Html.TextBoxFor(model => model.SurveyQuestions[i].SurveyName)
and add validation message
@Html.ValidationMessageFor(model => model.SurveyQuestions[i].SurveyName)
Scenario here is I create 5 textbox with for loop with same model property Surveyname and I want to validate only first textbox and no validations for rest of the textbox.
Is this possible?
Edit:
I used below code for rest of the textboxes but it validation occurs on these fields also.
@Html.TextBox("SurveyQuestions[" + i + "].Question", @Model.SurveyQuestions[i].Question)
Upvotes: 1
Views: 1863
Reputation: 6270
So finally I got the solutions, though I think it's not the correct way. But it solved my issue. Steps I did to fix the issue -
My final code looks like
@if (i == 0)
{
@Html.TextBoxFor(model => model.SurveyQuestions[i].Question, new Dictionary<string, object> { { "data-val-required", "required" }, { "data-val", "true" }, { "title", "Question " + (i + 1) }, {"class","QuestionTextBox"} })
<br />
@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) })
}
Upvotes: 2
Reputation: 58434
You need to create the first one with the following code as you did :
@Html.TextBoxFor(model => model.SurveyQuestions[i].SurveyName)
Then, use @Html.TextBox
for the rest of it. You just need to hardcode the id and name attributes for your model property.
Upvotes: 1