use*_*756 4 c# asp.net razor asp.net-mvc-3
嗨,大家好,我看过谷歌,雅虎,无法找到答案,为什么它是我的'@Html.ValidationMessageFor不起作用.当我运行应用程序时没有任何反应它允许输入所有内容.当我尝试编辑下面编辑视图中的项目时,它也会崩溃.我有以下内容:
<div class="editor-label">
@* @Html.LabelFor(model => model.Posted)*@
</div>
<div class="editor-field">
@Html.HiddenFor(model => model.Posted, Model.Posted = DateTime.Now)
@Html.ValidationMessageFor(model => model.sendinghome)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Cartypes)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Cartypes)
@Html.ValidationMessageFor(model => model.Cartypes)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.RegNum)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.RegNum)
@Html.ValidationMessageFor(model => model.RegNum)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Regprice)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Image)
@Html.ValidationMessageFor(model => model.Regprice)
</div>
Run Code Online (Sandbox Code Playgroud)
Ber*_*ron 33
以下是验证的工作原理.
假设您有以下型号:
public class MyModel {
[Required]
public string MyProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
请注意该Required属性,它是一个数据注释属性,指定该属性MyProperty是必填字段.
MyModel由以下视图(MyView.cshtml)使用:
@model MyNamespace.MyModel
@using (Html.BeginForm("MyAction", "MyController")) {
@Html.LabelFor(m => m.MyProperty)
@Html.TextBoxFor(m => m.MyProperty)
@Html.ValidationMessageFor(m => m.MyProperty)
<input type="submit" value="Click me">
}
Run Code Online (Sandbox Code Playgroud)
然后,当此表单发布到MyAction操作时MyController,将执行模型的验证.您需要做的是检查您的模型是否有效.可以使用ModelState.IsValid酒店完成.
[HttpPost]
public ActionResult MyAction(MyModel model) {
if (ModelState.IsValid) {
// save to db, for instance
return RedirectToAction("AnotherAction");
}
// model is not valid
return View("MyView", model);
}
Run Code Online (Sandbox Code Playgroud)
如果验证失败,将使用ModelState对象中存在的不同错误再次呈现视图.ValidationMessageFor助手将使用和显示这些错误.