当我尝试编辑项目时,@ Html.ValidationMessageFor崩溃 [英] @Html.ValidationMessageFor crashes when I try to edit an item

查看:61
本文介绍了当我尝试编辑项目时,@ Html.ValidationMessageFor崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的 @ Html.ValidationMessageFo 无法正常工作?当我运行该应用程序时,什么也没有发生,它允许输入所有内容.当我尝试在下面的编辑视图中编辑项目时,它也会崩溃.我有以下内容:

Why is my @Html.ValidationMessageFo not working? When I run the application, nothing happens and it allows everything to be entered. And it also crashes when I try to edit an item in my edit view, which is below. I have the following:

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

推荐答案

以下是验证的工作方式.

Here is how validation works.

假设您有以下模型:

public class MyModel {
    [Required]
    public string MyProperty { get; set; }
}

请注意 必需 属性,它是一个数据注释属性,用于指定 MyProperty 是必填字段.

MyModel :

@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">
}

然后,当此表单发布到 MyController MyAction 操作时,将执行模型验证.您要做的就是检查模型是否有效.可以使用 ModelState.IsValid 属性完成.

Then, when this form gets posted to the MyAction action of MyController, the validation of your model will be performed. What you have to do is check whether your model is valid or not. It can be done using the ModelState.IsValid property.

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

如果验证失败,则将使用 ModelState 对象中存在的不同错误再次渲染视图.这些错误将由 ValidationMessageFor 帮助器使用和显示.

If the validation failed, the view will be rendered again using the different errors that are present in the ModelState object. Those errors will be used and displayed by the ValidationMessageFor helper.

这篇关于当我尝试编辑项目时,@ Html.ValidationMessageFor崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆