Razor中的MVC数据注释 [英] MVC Data Annotations in Razor

查看:77
本文介绍了Razor中的MVC数据注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的MVC项目(Mono/.NET 4.5)中使用数据注释.我已经创建了模型并添加了所有适当的注释.我的视线和控制器已正确连接.但是,验证似乎没有发生.我已经尽力尝试了一切,但都无济于事.因为这是我第一次使用Razor和数据注释,所以我想我缺少一些设置文件,但我终生找不到.这是我的代码:

I'm trying to use Data Annotations in my MVC project (Mono/.NET 4.5). I've created my model and added all the appropriate annotations. I have my view and controller appropriately wired up. However, the validation just doesn't seem to be happening. I've tried everything I can find to no avail. As this is my first time working with Razor and Data Annotations, I imagine there is some setup piece I'm missing but I can't find it for the life of me. Here's my code:

模型

using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MyWebsite
{
  public class RegisterViewModel : BaseViewModel
  {
    #region properties
    [Required(ErrorMessage = "Required")]
    [StringLength(50)]
    [DisplayName("First Name")]
    public string FirstName { get; set; }
    [Required(ErrorMessage = "Required")]
    [StringLength(100)]
    [DisplayName("Last Name")]
    public string LastName { get; set; }
    [StringLength(50)]
    [DisplayName("Display Name")]
    public string DisplayName { get; set; }
    [Required(ErrorMessage = "Required")]
    [StringLength(255)]
    [DisplayName("Email Address")]
    public string EmailAddress { get; set; }
    #endregion

    #region ctor
    public RegisterViewModel ()
    {

    }
    #endregion

  }
}

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyWebsite.Controllers
{
  public class AccountController : Controller
  {
    public ActionResult Register()
    {
        ViewData ["IsComplete"] = false;
        ViewData ["RequiredVouches"] = WebSettings.RequiredVouches;

        return View ();
    }

    [HttpPost]
    public ActionResult Register(FormCollection formData)
    {
        if (ModelState.IsValid) {
            //TODO: Put the data
            ViewData ["IsComplete"] = true;
        }
        return View ();
    }
  }
}

查看

@model SummerIsles.Web.RegisterViewModel
@section Styles {
<link href="~/Content/themes/base/Account.css" rel="stylesheet" type="text/css" />
}
@{
if((bool)@ViewData["IsComplete"]) {
    <h1>Registration Request Complete!</h1>
    <div class="page-message">
        <p>
           Confirmation message goes here
        </p>
    </div>
}
else {
    <h1>Registration</h1>
    <div class="page-message">
        <p>
            Instruction text goes here
        </p>
    </div>
    using (Html.BeginForm()) {
        @Html.ValidationSummary(false)
        <fieldset>
            <legend>Your Information</legend>

            <div class="group column-1">
                @Html.LabelFor(modelItem => @Model.FirstName)
                @Html.EditorFor(modelItem => @Model.FirstName, new { htmlAttributes = new { @class="form-control" } } )
                @Html.ValidationMessageFor(modelItem => @Model.FirstName)

                @Html.LabelFor(modelItem => @Model.DisplayName)
                @Html.EditorFor(modelItem => @Model.DisplayName, new { htmlAttributes = new { @class="form-control" } } )
                @Html.ValidationMessageFor(modelItem => @Model.DisplayName)
            </div>

            <div class="group column-2">
                @Html.LabelFor(modelItem => @Model.LastName)
                @Html.EditorFor(modelItem => @Model.LastName, new { htmlAttributes = new { @class="form-control" } } )
                @Html.ValidationMessageFor(modelItem => @Model.LastName)

                @Html.LabelFor(modelItem => @Model.EmailAddress)
                @Html.EditorFor(modelItem => @Model.EmailAddress, new { htmlAttributes = new { @class="form-control" } } )
                @Html.ValidationMessageFor(modelItem => @Model.EmailAddress)
            </div>

            <div class="button-options">
                <button id="btnSubmit" type="submit" formmethod="post" class="btn btn-danger">Submit</button>
                <a id="btnCancel" href="~/" class="btn">Cancel</a>
            </div>
        </fieldset>
    }
  }
}

此外,我已经将jquery验证脚本添加到布局文件中,并且还在web.confg中启用了客户端验证.

Also, I have added the jquery validation scripts to my layout file and have also enabled client validation in the web.confg.

布局标题

<head>
  <!--some other css and such-->
  <script src="~/Scripts/jquery.validate.min.js"></script>
  <script src="~/Scripts/jquery.validate.unobstrusive.min.js"></script>
</head>

Web.config

<appSettings>
   <!--some other stuff-->
   <add key="ClientValidationEnabled" value="true" />
   <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

基本上,当我单击提交"时,它认为模型是完全有效的(ModelState.IsValid在控制器中返回true),而验证的东西(我希望在发回到控制器之前会触发)不会出现.即使使用完全空白的表单(尽管具有"Required"数据注释),我也没有收到任何验证消息.我想念什么?

Basically, when I click submit, it thinks the model is perfectly valid (ModelState.IsValid returns true in the controller) and the validation stuff (which I would expect to fire before the post back to the controller) never seems to fire. I get no validation messages even with a completely blank form (despite having the "Required" data annotation). What am I missing?

推荐答案

@Html.ValidationMessageFor(modelItem => @Model.LastName)

应该是

@Html.ValidationMessageFor(modelItem => modelItem.LastName)

用于 all 您的HtmlHelpers,包括TextBoxFor和LabelFor等.

for all your HtmlHelpers, including TextBoxFor and LabelFor etc.

public ActionResult Register(FormCollection formData)

应该是

public ActionResult Register(RegisterViewModel model)

为了使服务器端ModelState.IsValid正常工作.

in order for your server side ModelState.IsValid to work.

这篇关于Razor中的MVC数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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