Asp.net MVC3 validation

2019-08-05 00:58发布

问题:

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)

回答1:

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 -

  1. 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"
  2. Then I added these fields to textbox which needs to be validated.
  3. Then I added Html.Validation() for textbox with validation message.

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) })    
                }


回答2:

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.