AspNet MVC4 教学-18:Asp.Net MVC4 客户端验证和服务端验证快速Demo

A.首先创建Basic类型的mvc项目.

B.创建Model:

Student.cshtml:

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

namespace MvcRenderTest.Models
{
    public class Student
    {
        [Display(Name = "姓名")]    //设置要显示的字段名
        [Required(ErrorMessage = "您需要填写{0}")]  //设置为必须字段 已经错误提示
        [StringLength(50, MinimumLength = 2)]     //设置最大长度和最小长度
        public string Name { get; set; }

        [Display(Name = "年龄")]
        [Range(14, 70, ErrorMessage = "年龄填写不正确!")]  //设置 值范围
        public int Age { get; set; }

        [Display(Name = "身高")]
        [Range(typeof(decimal), "1.20", "2.50", ErrorMessage = "身高超出指定范围")]
        public decimal Height { get; set; }

        [Display(Name = "生日")]
        [DataType(DataType.Date, ErrorMessage = "{0}格式不正确")]  //设置数据类型以及错误提示
        public DateTime Birthday { get; set; }

        [Display(Name = "电话")]
        [Remote("CheckPhone", "Student", ErrorMessage = "{0}已被注册")]   //在指定的Conteroller中的通道(route)中验证数据
        public string Phone { get; set; }

        [Display(Name = "地址")]
        [DataType(DataType.MultilineText)]
        public string Address { get; set; }

        [Display(Name = "电子邮箱")]
        [RegularExpression(@"(\w)+(\.\w+)*@(\w)+((\.\w+)+)", ErrorMessage = "{0}格式不正确")]  //正则验证
        public string Email { get; set; }

        [Display(Name = "再次输入电子邮箱")]
        [Compare("Email", ErrorMessage = "{0}两次输入不一致")]   //设置比较两个字段的值
        public string EmailConfirm { get; set; }

        [Display(Name = "密码")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "备用电子邮箱")]
        [DataType(DataType.EmailAddress, ErrorMessage = "{0}格式不正确")]
        public string email_B { get; set; }
  
    }
}

Phone.cshtml:

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

namespace MvcRenderTest.Models
{
    public class Phone
    {
        public int ID { set; get; }
        public string PhoneNum { set; get; }
    }
}


C.创建Controller:

HomeController.cs:

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

namespace MvcRenderTest.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

    }
}
StudentController.cs:

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

namespace MvcRenderTest.Controllers
{
    public class StudentController : Controller
    {
        //
        // GET: /Student/
        private MvcRenderTestContext db = new MvcRenderTestContext();
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Student/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }
        public JsonResult CheckPhone(string Phone)
        {
            var result = false;
            if((db.Phones.Where(m=>m.PhoneNum==Phone).Count())==0)
            {
                result = true;
            }            
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        //
        // GET: /Student/Create

        public ActionResult Create()
        {
            return View("Create");
        }
        public ActionResult Create2()
        {
            return View("Create2");
        }
        //
        // POST: /Student/Create

        [HttpPost]
        public ActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                if (student.Name == "奥巴马")
                {
                    ModelState.AddModelError("", "奥巴马名称禁用.");
                    return View();
                }


                if (student.Name == "张三")
                {
                    ModelState.AddModelError("Name", "您的名字好奇特");
                    return View();
                }
                return View("OK");
            }
            else
            {
                return View();
            }
        }

        //
        // GET: /Student/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Student/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Student/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Student/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
PhoneCtrolloller.cs:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcRenderTest.Models;

namespace MvcRenderTest.Controllers
{
    public class PhoneController : Controller
    {
        private MvcRenderTestContext db = new MvcRenderTestContext();

        //
        // GET: /PhoneNum/

        public ActionResult Index()
        {
            return View(db.Phones.ToList());
        }

        //
        // GET: /PhoneNum/Details/5

        public ActionResult Details(int id = 0)
        {
            Phone phone = db.Phones.Find(id);
            if (phone == null)
            {
                return HttpNotFound();
            }
            return View(phone);
        }

        //
        // GET: /PhoneNum/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /PhoneNum/Create

        [HttpPost]
        public ActionResult Create(Phone phone)
        {
            if (ModelState.IsValid)
            {
                db.Phones.Add(phone);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(phone);
        }

        //
        // GET: /PhoneNum/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Phone phone = db.Phones.Find(id);
            if (phone == null)
            {
                return HttpNotFound();
            }
            return View(phone);
        }

        //
        // POST: /PhoneNum/Edit/5

        [HttpPost]
        public ActionResult Edit(Phone phone)
        {
            if (ModelState.IsValid)
            {
                db.Entry(phone).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(phone);
        }

        //
        // GET: /PhoneNum/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Phone phone = db.Phones.Find(id);
            if (phone == null)
            {
                return HttpNotFound();
            }
            return View(phone);
        }

        //
        // POST: /PhoneNum/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Phone phone = db.Phones.Find(id);
            db.Phones.Remove(phone);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
D.相应的View文件:

Home/Index.cshtml:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<h2>@Html.ActionLink("Phone Num","Index","Phone")</h2>
<h2>@Html.ActionLink("Create学生","Create","Student")</h2>
<h2>@Html.ActionLink("Create学生2","Create2","Student")</h2>

Student/Create.cshtml:

@model MvcRenderTest.Models.Student

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

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

    <fieldset>
        <legend>Student</legend>

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

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

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

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

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

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

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

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

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

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

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

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

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

Student/Create2.cshtml:

@model MvcRenderTest.Models.Student

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {

       @Html.EditorForModel()
        <p>
            <input type="submit" value="Create" />
        </p>

}

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Student/OK.cshtml:

@{
    ViewBag.Title = "OK";
}

<h2>验证OK!</h2>
<h2>@Html.ActionLink("Index","Index","Home")</h2>
--------------------------

注意:利用Model中的Phone类,采用EntityFramework技术,创建相应的Controller,与数据库有关的上下文.并产生相应的View文件.

下面抓图看解决方案目录:

E.通过Web.config内容的修改,观察页面提交后,刷新按钮状态的变化:

 <add key="ClientValidationEnabled" value="true" />
 <add key="UnobtrusiveJavaScriptEnabled" value="true" />
F.通过修改网页浏览器的Javascript的禁用和启用,观察页面提交后,刷新按钮状态的变化.








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gCodeTop 格码拓普 老师

您的鼓励.我的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值