mvc 前端校验

首先解决 Ajax.BeginFor异步提交表单,给表单添加样式的问题。不能直接用class属性,网上找了很多都是用ClassName,经过测试不管用,看源代码发现生成的是ClassName而非class,其实很简单,加一个@符号即可,即@class="";

我们知道,LabelFor是不能添加class样式的,这个需自行拓展,反编译后自行拓展了一个给LabelFor添加样式的方法,代码如下:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Expressions; namespace System.Web.Mvc
{
public static class MyLabelExtensions
{
public static MvcHtmlString MyLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string className)
{
return LabelHelper(html, ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData), ExpressionHelper.GetExpressionText(expression), className);
} private static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string className = "")
{
string txtLabel = metadata.DisplayName ??
(metadata.PropertyName ?? htmlFieldName.Split(new char[] {','}).Last<string>());
if (string.IsNullOrEmpty(className))
{
return MvcHtmlString.Empty;
}
TagBuilder tagBuilder = new TagBuilder("label");
tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
tagBuilder.Attributes.Add("class", className);
tagBuilder.SetInnerText(txtLabel);
return new MvcHtmlString(tagBuilder.ToString(TagRenderMode.Normal));
}
}
}

先看效果:

mvc 前端校验

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#代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Runtime.Serialization;
using System.ComponentModel; namespace MvcApp.DataTable.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/ public ActionResult Index()
{
ViewBag.SexList = new List<KeyValue>
{
new KeyValue("","男"),new KeyValue("","女")
};
return View();
} [HttpPost]
public ActionResult SetRecord(MyTest t)
{
string m = t.Name;
return Content("ok");
} [HttpPost]
public ActionResult GetSameNameCount()
{
string Name = Request["Name"];
bool isExistName = true;//验证通过
if (Name == "huangzhong")
{
isExistName = false;//用户名已存在,验证不通过
}
System.Web.Script.Serialization.JavaScriptSerializer javascriptserializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return Content(javascriptserializer.Serialize(isExistName));
}
}
[DataContract]
public class MyTest
{
[DataMember]
[DisplayName("姓名")]
public string Name { get; set; }
[DataMember]
[DisplayName("邮箱")]
public string Email { get; set; }
[DataMember]
[DisplayName("主题")]
public string Subject { get; set; }
[DataMember]
[DisplayName("地址")]
public string Address { get; set; }
[DataMember]
[DisplayName("密码")]
public string Password { get; set; }
[DataMember]
[DisplayName("确认密码")]
public string Password2 { get; set; }
[DataMember]
[DisplayName("性别")]
public string Sex { get; set; }
} public class KeyValue
{
public string strKey { get; set; }
public string strValue { get; set; }
public KeyValue(string iv, string it)
{
this.strKey = iv;
this.strValue = it;
}
}
}
上一篇:用php生成静态html页面(通用2种方法)


下一篇:不同css样式适应不同屏幕大小实现自适应宽度