首先解决 Ajax.BeginFor异步提交表单,给表单添加样式的问题。不能直接用class属性,网上找了很多都是用ClassName,经过测试不管用,看源代码发现生成的是ClassName而非class,其实很简单,加一个@符号即可,即@class="";
我们知道,LabelFor是不能添加class样式的,这个需自行拓展,反编译后自行拓展了一个给LabelFor添加样式的方法,代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using System.Linq.Expressions; 7 8 namespace System.Web.Mvc 9 { 10 public static class MyLabelExtensions 11 { 12 public static MvcHtmlString MyLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string className) 13 { 14 return LabelHelper(html, ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData), ExpressionHelper.GetExpressionText(expression), className); 15 } 16 17 private static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string className = "") 18 { 19 string txtLabel = metadata.DisplayName ?? 20 (metadata.PropertyName ?? htmlFieldName.Split(new char[] {','}).Last<string>()); 21 if (string.IsNullOrEmpty(className)) 22 { 23 return MvcHtmlString.Empty; 24 } 25 TagBuilder tagBuilder = new TagBuilder("label"); 26 tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName))); 27 tagBuilder.Attributes.Add("class", className); 28 tagBuilder.SetInnerText(txtLabel); 29 return new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal)); 30 } 31 } 32 }
先看效果:
CSS
label.valid { width: 24px; height: 24px; background: url(assets/img/valid.png) center center no-repeat; display: inline-block; text-indent: -9999px; } label.error { font-weight: bold; color: red; padding: 2px 8px; margin-top: 2px; }
前端JS代码:
@{
Layout = null;
}
@model MvcApp.DataTable.Controllers.MyTest
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link href="../../JQueryValidate/assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="../../JQueryValidate/style.css" rel="stylesheet" type="text/css" />
<script src="../../JQueryValidate/assets/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../JQueryValidate/assets/js/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript" charset="gb2312">
$(document).ready(function() {
$('#contact-form').validate({
rules: {
Name: {
minlength: 2,
required: true,
remote: {
url: "/Home/GetSameNameCount/",
type: "post",
data: {
Name: function () {
return $('#Name').val();
}
}
}
},
Email: {
required: true,
email: true
},
Subject: {
minlength: 2,
required: true
},
Password: {
required: true,
minlength: 5
},
Password2: {
required: true,
minlength: 5,
equalTo: "#Password"
},
Address: {
minlength: 2,
required: true
}
},
messages: {
Name: {
minlength: "请输入长度至少2位",
required: "名称必须的必!",
remote: "姓名已存在,请输入其他名称"
},
Email: {
required: "请输入邮箱地址",
email: "邮箱格式有误,请仔细检查"
},
Subject: {
minlength: "请输入长度至少2位",
required: "Must Write Subject Please"
},
Password: {
required: "请输入密码",
minlength: "密码长度至少为5位数"
},
Password2: {
required: "请再次输入密码",
minlength: "密码长度至少为5位数",
equalTo: "两次密码输入不一致"
},
Address: {
minlength: "请输入长度至少2位",
required: "消息不能为空撒"
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
element
.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});
function afterSave() {
}
</script>
</head>
<body>
@using (Ajax.BeginForm("SetRecord", "Home", new AjaxOptions { UpdateTargetId = "ajaxResult", HttpMethod = "POST", InsertionMode = InsertionMode.Replace, OnSuccess = "afterSave" }, new { id = "contact-form", @class = "form-horizontal" }))
{
<div class="control-group">
@Html.MyLabelFor(model => model.Name, "control-label")
<div class="controls">
@Html.TextBoxFor(model => model.Name, new { @class="input-xlarge" })
</div>
</div>
<div class="control-group">
@Html.MyLabelFor(model => model.Email, "control-label")
<div class="controls">
@Html.TextBoxFor(model => model.Email, new { @class="input-xlarge" })
</div>
</div>
<div class="control-group">
@Html.MyLabelFor(model => model.Subject, "control-label")
<div class="controls">
@Html.TextBoxFor(model => model.Subject, new { @class="input-xlarge" })
</div>
</div>
<div class="control-group">
@Html.MyLabelFor(model => model.Password, "control-label")
<div class="controls">
@Html.TextBoxFor(model => model.Password, new { @class = "input-xlarge", type = "password" })
</div>
</div>
<div class="control-group">
@Html.MyLabelFor(model => model.Password2, "control-label")
<div class="controls">
@Html.TextBoxFor(model => model.Password2, new { @class = "input-xlarge", type = "password" })
</div>
</div>
<div class="control-group">
@Html.MyLabelFor(model => model.Address, "control-label")
<div class="controls">
<textarea class="input-xlarge" name="Address" id="Address" rows="3"></textarea>
</div>
</div>
<div class="form-group">
@Html.MyLabelFor(model => model.Sex, "control-label")
@Html.DropDownListFor(model => model.Sex, new SelectList(ViewBag.SexList, "strKey", "strValue", 1), "--请选择--", new { style = "width: 280px;" })
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">提交</button>
<button type="reset" class="btn">重置</button>
</div>
}
</body>
</html>
后台C#代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 using System.Runtime.Serialization; 7 using System.ComponentModel; 8 9 namespace MvcApp.DataTable.Controllers 10 { 11 public class HomeController : Controller 12 { 13 // 14 // GET: /Home/ 15 16 public ActionResult Index() 17 { 18 ViewBag.SexList = new List<KeyValue> 19 { 20 new KeyValue("0","男"),new KeyValue("1","女") 21 }; 22 return View(); 23 } 24 25 [HttpPost] 26 public ActionResult SetRecord(MyTest t) 27 { 28 string m = t.Name; 29 return Content("ok"); 30 } 31 32 [HttpPost] 33 public ActionResult GetSameNameCount() 34 { 35 string Name = Request["Name"]; 36 bool isExistName = true;//验证通过 37 if (Name == "huangzhong") 38 { 39 isExistName = false;//用户名已存在,验证不通过 40 } 41 System.Web.Script.Serialization.JavaScriptSerializer javascriptserializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 42 return Content(javascriptserializer.Serialize(isExistName)); 43 } 44 } 45 [DataContract] 46 public class MyTest 47 { 48 [DataMember] 49 [DisplayName("姓名")] 50 public string Name { get; set; } 51 [DataMember] 52 [DisplayName("邮箱")] 53 public string Email { get; set; } 54 [DataMember] 55 [DisplayName("主题")] 56 public string Subject { get; set; } 57 [DataMember] 58 [DisplayName("地址")] 59 public string Address { get; set; } 60 [DataMember] 61 [DisplayName("密码")] 62 public string Password { get; set; } 63 [DataMember] 64 [DisplayName("确认密码")] 65 public string Password2 { get; set; } 66 [DataMember] 67 [DisplayName("性别")] 68 public string Sex { get; set; } 69 } 70 71 public class KeyValue 72 { 73 public string strKey { get; set; } 74 public string strValue { get; set; } 75 public KeyValue(string iv, string it) 76 { 77 this.strKey = iv; 78 this.strValue = it; 79 } 80 } 81 }