Part 89 - Remote validation in asp.net mvc

远程验证用户名
本文介绍如何使用ASP.NET MVC的RemoteAttribute实现远程验证用户名唯一性。通过创建数据库表、实体模型及控制器,结合前端验证脚本,确保用户注册时输入的用户名未被占用。

Sometimes, to check if a field value is valid, we may need to make a database call.A classic example of this is the user registration page. To register a user, we need a unique username. So, to check, if the username is not taken already, we have to make a call to the server and check the database table. RemoteAttribute is useful in situations like this. 

Example: When a user provides a username that already exists, the associated validation error message should be displayed immediately as shown below. 


Step 1: Create tblUsers table
Create table tblUsers
(
[Id] int primary key identity,
[FullName] nvarchar(50),
[UserName] nvarchar(50),
[Password] nvarchar(50)
)

Step 2: Create an ado.net entity data model using table tblUsers. Upon creating the entity model, change the name of the entity from to User. Save changes and build the solution.

Step 3: Add HomeController with the following settings
1. controller Name = HomeController
2. Template = MVC controller with read/write actions and views, using Entity Framework
3. Model Class = User (MVCDemo.Models)
4. Data context class = SampleDBContext (MVCDemo.Models)
5. Views = Razor

Step 4: Copy and paste the following function in HomeController. This is the method which gets called to perform the remote validation. An AJAX request is issued to this method. If this method returns true, validation succeeds, else validation fails and the form is prevented from being submitted. The parameter name (UserName) must match the field name on the view. If they don't match, model binder will not be able bind the value with the parameter and validation may not work as expected.
public JsonResult IsUserNameAvailable(string UserName)
{
    return Json(!db.Users.Any(x => x.UserName == UserName),
                                         JsonRequestBehavior.AllowGet);
}

Step 5: Right click on the Models folder and a class file with name = User.cs. Copy and paste the following code. Notice that the name of the method (IsUserNameAvailable) and the controller name (Home) and error message are passed as arguments to Remote Attribute
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MVCDemo.Models
{
    [MetadataType(typeof(UserMetaData))]
    public partial class User
    {
    }

    public class UserMetaData
    {
        [Remote("IsUserNameAvailable""Home", ErrorMessage="UserName already in use.")]
        public string UserName { get; set; }
    }
}

Step 6: Include references to the following css and script files in Create.cshtml view. jQueryjquery.validate and jquery.validate.unobtrusive script files are required for remote validation to work.
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>

Step 7: Make sure ClientValidation and UnobtrusiveJavaScript are enabled in web.config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" /> 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值