asp.net mvc 唯一性验证

刚接触asp.net mvc,很多地方都不懂,边写边学习,有不对的地方请多多指正。

问题

用户唯一性验证,新建用户时判断用户名唯一性,修改时用户名不进行修改,所以不需要验证,搞了半天才找到适合的方法,网上找了一下,有用Remote Validation的,也有用ValidationAttribute的,都试了一下,ValidationAttribute是保存后校验,感觉有点怪味道,Remote Validation是客户端验证,符合我的需要。下面是Remote Validation实现的唯一性验证。

实现

Remote控制器

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

namespace MVC.Controllers
{
    public class MyRemoteController : Controller
    {
        // GET: MyRemote
        public JsonResult RemoteValidate(string name) //这里的参数名字,必须要和视图中文本框控件的名字一样,但大小写无所谓
        {
            //如果存在用户名,即isExists=true
            bool isExists = MyRemoteStaticData.RemoteList.
                Where(s => s.Name.ToLowerInvariant().
                    Equals(name.ToLower())).FirstOrDefault() != null;
            //就向前台返回false,表明已经存在userName
            return Json(!isExists,JsonRequestBehavior.AllowGet);
        }
}

model实体

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

namespace MVC.Models
{
    public class User
    {
        [Remote("RemoteValidate", "MyRemote", ErrorMessage = "抱歉用户名已经存在!请重新输入!!!")]
        public string Name { get; set; }
        public string Email { get; set; }
    }
}

新建视图

@model MVC.Models.User

@{
    ViewBag.Title = "新建用户";
}

新建用户

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

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model =>model.Name, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Email , htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
  
} @section Scripts { @Scripts.Render("~/bundles/jqueryval") }

修改视图,这里用户名设置为隐藏

@model MVC.Models.User

@{
    ViewBag.Title = "用户信息修改";
}

用户信息修改

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

@Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.Id) @Html.HiddenFor(model => model.Name)
@Html.LabelFor(model => model.Mail, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Mail, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Mail, "", new { @class = "text-danger" })
  
} @section Scripts { @Scripts.Render("~/bundles/jqueryval") }

参考
MVC学习系列13--验证系列之Remote Validation

你可能感兴趣的:(asp.net mvc 唯一性验证)