MVC学习笔记——快速建立客户端验证

直接上代码 首先是Model
public class Auction
    {
        [Display(Name="序号")]
        [Required,StringLength(50,
            ErrorMessage="Title cannot be longer then 50 characters")]
        [Key]
        [DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        public long id { get; set; }
        [Display(Name = "标题"),Required]
        public string Title { get; set; }
        [Display(Name = "描述")]
        public string Description { get; set; }
        [Display(Name = "初始价格"),Range(1,10000)]
        public decimal StartPrice { get; set; }
        [Display(Name = "当前价格"),Range(1,10000)]
        public decimal CurrentPrice { get; set; }
        [Display(Name = "开始时间"),Range(typeof(DateTime),"1/1/2012","12/31/3000")]
        public DateTime StartTime { get; set; }
        [Display(Name = "结束时间"), Range(typeof(DateTime), "1/1/2012", "12/31/3000")]
        public DateTime EndTime { get; set; }
    }

再是controller

[System.Web.Mvc.HttpGet]
        public ActionResult Create()
        {

            return View();
        }

        [HttpPost]
        public ActionResult Create(Auction auction)
        {
            if (auction.EndTime <= DateTime.Now.AddDays(-1))
            {
                ModelState.AddModelError(
                    "EndTime",
                    "Auction must be at least one day long."
                    );
            }
            if (ModelState.IsValid)
            {
                var db = new AuctionsContext();
                db.Auctions.Add(auction);
                db.SaveChanges();
                return RedirectToAction("Index");

            }
            return View(auction);
        }


最后是View

@model Ebuy.Website.Models.Auction

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Auction</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Title)
            @Html.ValidationMessageFor(model => model.Title,"*")
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description, "*")
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.StartPrice)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.StartPrice)
            @Html.ValidationMessageFor(model => model.StartPrice)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.CurrentPrice)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CurrentPrice)
            @Html.ValidationMessageFor(model => model.CurrentPrice)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.StartTime)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.StartTime)
            @Html.ValidationMessageFor(model => model.StartTime)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.EndTime)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EndTime)
            @Html.ValidationMessageFor(model => model.EndTime)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
需要注意的是我这里使用的是MVC4,单独解释一下这段代码

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Create页面引用的模板页_Layout.cshtml ,在这个模板页中申明了一个section。

@RenderSection("scripts", required: false)

在BundleConfig.cs中我们绑定了一个包名字叫“~/bundles/jqueryval”

//客户端验证组件
            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));
最后注意在config中打开jquery验证

<appSettings>
    
    <!--验证模块-->
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
        总结一下,首先我们在Model中对需要验证的字段添加对应的Attribute,第二我们在客户端引用相应的验证脚本(jquery、jquery.validate、jquery.unobtrusive),最后记得在config中设置打开客户端验证。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值