Asp.net MVC3验证 [英] Asp.net MVC3 validation
问题描述
我有asp.net MVC3应用验证的地方通过在模型添加验证属性来完成。
例如。
[必需(的ErrorMessage =必填字段)
[显示(NAME =SurveyName)]
[数据类型(DataType.Text)
公共字符串SurveyName {获取;设置;}
然后,我创建鉴于文本框
@ Html.TextBoxFor(型号=> model.SurveyQuestions [I] .SurveyName)
和添加验证信息
@ Html.ValidationMessageFor(型号=> model.SurveyQuestions [I] .SurveyName)
下面是场景创建文本框5与同样具有模型属性Surveyname循环,我想验证只有第一个文本框和文本框的其余部分没有验证。
这可能吗?
编辑:
我用低于code为文本框的其余部分,但它发生在这些领域也验证。
@ Html.TextBox(SurveyQuestions [+ I +]。提问,@ Model.SurveyQuestions [I]。提问)
所以最后我得到了解决,但我认为这是不正确的方法。但它解决了我的问题。
我的步骤做,以解决这个问题 -
- 我观察到的HTML对此有一个验证错误输入字段。输入字段将有额外的属性,例如数据-VAL-要求和数据val的
- 然后我说这些领域的文本框,需要进行验证。
- 然后我说Html.Validation()为文本框与验证消息。
我的最后code看起来像
@if(我== 0)
{
@ Html.TextBoxFor(型号=> model.SurveyQuestions [I]。提问,新的字典<字符串对象> {{数据-VAL-要求的,需要},{数据-VAL,真 },{称号,问题+(I + 1)},{类,QuestionTextBox}})
< BR />
@ Html.ValidationMessage(SurveyQuestions [0]。提问,至少需要一个问题。)
}
其他
{
@ Html.TextBoxFor(型号=> model.SurveyQuestions [I]。提问,新{@class =QuestionTextBox@title =问题+(I + 1)})
}
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)
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 -
- 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 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) })
}
这篇关于Asp.net MVC3验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!