代码改变世界

ASP.NET MVC 3 中 RemoteAttribute 的使用 Demo

2012-03-29 17:44  音乐让我说  阅读(624)  评论(0编辑  收藏  举报

直接贴代码了,代码能说明一切。

第一步:

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

namespace DearBruce.Mvc3FunctionsRometeDemo.MvcUI.Models
{
/// <summary>
/// 用户添加操作的模型
///
/// </summary>
///
public class SysUserInfo
{
/// <summary>
/// 用户名
/// </summary>
[DisplayName("登录账号")]
[Required(ErrorMessage = "用户账号不能为空")]
[Remote("CheckUserAccountExists", "Home", ErrorMessage = "用户账号已存在")] // 远程验证(Ajax)
public string UserAccount { get; set; }
}
}

 

第二步:

    public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(new SysUserInfo());
}

[HttpPost]
public ActionResult Index(SysUserInfo sysInfo)
{
if(ModelState.IsValid)
{
return Content("提交成功!");
}
return View(sysInfo);
}

/// <summary>
/// 校验用户帐号是否已经存在,返回值为 true 表示验证通过,false 表示验证失败
/// </summary>
/// <param name="userAccount"></param>
/// <returns></returns>
[HttpGet] // 只能用GET !!!
public ActionResult CheckUserAccountExists(string userAccount)
{
string[] existsUsers = { "bruce", "liu", "winner"};

bool exists = existsUsers.Contains(userAccount, StringComparer.CurrentCultureIgnoreCase);
ActionResult ar;
//ar = Json(!exists, JsonRequestBehavior.AllowGet);
// 或者
ar = Content(exists ? "false" : "true");
return ar;
}
}

 

第三步:

@{
ViewBag.Title = "主页";
}

@model DearBruce.Mvc3FunctionsRometeDemo.MvcUI.Models.SysUserInfo

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

<fieldset>
<legend>添加用户</legend>
<div>
@using(Html.BeginForm("Index","Home"))
{
<p>
@Html.LabelFor(m=>m.UserAccount):
@Html.TextBoxFor(m=>m.UserAccount)
@Html.ValidationMessageFor(m=>m.UserAccount)
</p>
<p>
<input type="submit" value="提 交" />
</p>
}
</div>
</fieldset>

 


响应信息:

 

Demo 下载:https://files.cnblogs.com/Music/Mvc3_Functions_RometeAttribute_Demo.rar

 

谢谢浏览!