前台页面代码:
@{
ViewBag.Title = "资源库-用户添加页";
//指定布局页
Layout = "~/Areas/Admin/Views/Shared/_LayoutAdmin.cshtml";
}
@using (Html.BeginForm())
{
<div class="m-content">
<div class="m-form f-cb">
<dl class="f-cb s-borderbg">
<dt><i>*</i>登录名:</dt>
<dd>
@Html.TextBoxFor(model => model.CLOGINNAME, new { @class = "u-iptm", @maxlength = "25" })
@Html.ValidationMessageFor(model => model.CLOGINNAME)
</dd>
<dt><i>*</i>密码:</dt>
<dd>
@Html.TextBoxFor(model => model.CPASSWORD, new { @class = "u-iptm", Value = "123456", @maxlength = "25" })
@Html.ValidationMessageFor(model => model.CPASSWORD)
</dd>
<dt></dt>
<dd>
<input type="submit" value="保存" class="u-btnblue" />
<input type="button" value="取消" class="u-btnblue marl10" οnclick="location.href='/admin/user/index';" />
</dd>
</dl>
</div>
</div>
}
实体类:
public partial class RS_USER
{
/// <summary>
///
/// </summary>
[LengthCheck(0,12,ErrorMessage="* 不能超过12个字符!")]
public string CLOGINNAME { get; set; }
/// <summary>
///
/// </summary>
public string CPASSWORD { get; set; }
}
LengthCheckAttribute.cs类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace MyResource.Attributes
{
public class LengthCheckAttribute : RangeAttribute, IClientValidatable
{
public LengthCheckAttribute(int minimum, int maximum) : base(minimum, maximum) { }
//后台验证
public override bool IsValid(object value)
{
bool bResult = true;
if (value != null)
{
String str = (String)value;
int length = GetByteLength(str);
bResult = str.Length <= (int)this.Maximum;
}
return bResult;
}
//验证错误信息
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(name);
}
//客户端验证
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule validationRule = new ModelClientValidationRule() { ValidationType = "lengthcheck", ErrorMessage = FormatErrorMessage(metadata.DisplayName) };
validationRule.ValidationParameters.Add("length",this.Maximum);
yield return validationRule;
}
public int GetByteLength(string str)
{
//使用Unicode编码的方式将字符串转换为字节数组,它将所有字符串(包括英文中文)全部以2个字节存储
byte[] bytestr = System.Text.Encoding.Unicode.GetBytes(str);
int j = 0;
for (int i = 0; i < bytestr.GetLength(0); i++)
{
//取余2是因为字节数组中所有的双数下标的元素都是unicode字符的第一个字节
if (i % 2 == 0)
{
j++;
}
else
{
//单数下标都是字符的第2个字节,如果一个字符第2个字节为0,则代表该Unicode字符是英文字符,否则为中文字符
if (bytestr[i] > 0)
{
j++;
}
}
}
return j;
}
}
}
后台Controller代码:略。