博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
带验证的mvc razor 文本框扩展组件
阅读量:6289 次
发布时间:2019-06-22

本文共 26890 字,大约阅读时间需要 89 分钟。

在做 mvc 3 razor有时候,有大量的数据需要验证.当然也有JQ的验证插件和系统的一些方法.本文主要讲自定的一个一组件

预浏效果如下

这个组件的基本原理是用JS做为外挂验证,加以CSS美化其功能

首先我们要做的是美化这个文本框的样式,比如说有默认样式 焦点,成功,失败几种样式,以及旁边的 tooltip 提示样式

CSS如下

1 .webUITooltip{
background:url(images/wBottomLeft.gif) no-repeat 0 bottom;overflow:hidden;position:absolute;top:-8px} 2 .webUITooltip .webUITooltipRight{
background:url(images/wBottomRight.gif) no-repeat right bottom} 3 .webUITooltip .webUITooltipTop{
background:url(images/wTopLeft.gif) no-repeat 0 0} 4 .webUITooltip .webUITooltipTopRight{
background:url(images/wTopRight.gif) no-repeat right 0;padding:12px 14px 14px 19px;overflow:hidden;font:normal 12px/1.6 '\5b8b\4f53'} 5 .webUITooltips{
background:url(images/yBottomLeft.gif) no-repeat 0 bottom} 6 .webUITooltips .webUITooltipRight{
background:url(images/yBottomRight.gif) no-repeat right bottom} 7 .webUITooltips .webUITooltipTop{
background:url(images/yTopLeft.gif) no-repeat 0 0} 8 .webUITooltips .webUITooltipTopRight{
background:url(images/yTopRight.gif) no-repeat right 0} 9 .webUITxtBox{
border:1px solid #ccc;height:18px;line-height:16px;width:160px;text-indent:4px;background:#fff} 10 .webUITxtBox.onerror{
background:#FEEAEB url(images/rpple.gif) repeat-x 0 bottom} 11 .webUITxtBox.onfocus{
background:#DFEEFD;border-color:#359AFF} 12 .webUITxtBox.onSuccess{
border-color:#41CE33;background:#E7FDE5} 13 .webUITooltipTips,.webUISuccess,.webUIError{
font:normal 12px/20px '\5b8b\4f53';text-indent:25px;overflow:hidden;height:20px;background:url(images/ico.gif) no-repeat;white-space:nowrap} 14 .webUITooltipTips{
background-position:0 -20px} 15 .webUIError{
background-position:0 -40px} 16 .webUILabelFor{
display:none} 17 textarea{
overflow:auto}

有用到的JS代码

/*     说明:WebUI 文本框(自定义多重验证,Tootip)    作者:DEVIN    主页:http://www.21v.org    版权:Devin!JS 2.0 Bate (C) Skyline Co.,Ltd  2011.11.28 */String.prototype.format = function () {    var args = arguments;    return this.replace(/\{(\d+)\}/g, function (m, i) {        return args[i];    });};String.prototype.trim = function () {    return this.replace(/(^\s*)|(\s*$)/g, "");};if (!Array.indexOf) {    Array.prototype.indexOf = function (Object) {        for (var i = 0; i < this.length; i++) {            if (this[i] == Object) {                return i;            }        }        return -1;    };};var Textbox = function (ini) {    this.Type = ini.Type || null;    this.Container = ini.Container || null;    this.Properties = ini.Properties || null;    this.Style = ini.Style || null;    this.CSS = ini.CSS || null;    this.Verification = ini.Verification || null;    this.Id = this.Properties.id || this.Properties.Id || '';    this.Value = '';    this.Callback = ini.Callback || null;    Textbox.Controls = Textbox.Controls || [];    Textbox.Regexs = Textbox.Regexs || [];    Textbox.Zindex = Textbox.Zindex || 666;    Textbox.Tooltips = Textbox.Tooltips || [];    Textbox.Zindex--;    Textbox.IsValid = Textbox.IsValid || false;    Textbox.GetURL = Textbox.GetURL || '';    this.init();};Textbox.GetControl = function (c) {    var x = eval('({0})'.format(c));    for (var o in x) {        return o ? o : '';    }};Textbox.AddEvent = function (o, a, b) {    o.attachEvent ? o.attachEvent('on' + a, function () {        b.call(o)    }) : o.addEventListener(a, b, false)};Textbox.Validation = function () {    Textbox.IsValid = true;    var $ = this.prototype;    var s = [];    for (var i = 0; i < Textbox.Regexs.length; i++) {        var r = Textbox.Regexs[i];        var id = Textbox.GetControl(Textbox.Controls[i]);        var tx = document.getElementById(id);        var er = document.getElementById('__' + id);        var index = -1;        for (var j = 0; j < r.length; j++) {            var reg = r[j];            if (reg.Regex.test(tx.value)) {                continue;            }            index = index > -1 ? index : j;            Textbox.IsValid = false;        }        s.push('{0}={1}'.format(id, escape(tx.value)));        var __ = r[index];        var c = tx.className;        c = c.replace(/\s*(onfocus|onerror|onSuccess)/, '');        if (index != -1) {            tx.className = c + ' onerror';            er.innerHTML = $.tools.Error.format(__.Error);        } else {            tx.className = c + ' onSuccess';            er.innerHTML = $.tools.Success.format('输入正确');        }    }    Textbox.GetURL = s.join('&');};Textbox.Getpos = function (o) {    var x = 0, y = 0;    o = typeof (o) == 'string' ? document.getElementById(o) : o;    if (!o) {        return { 'x': x, 'y': y }    }    x = o.offsetWidth + 10;    do {        x += o.offsetLeft;        y += o.offsetTop    }    while ((o = o.offsetParent))    {        return { 'x': x, 'y': y }    }};Textbox.ReSize = function () {    for (var i = 0; i < Textbox.Tooltips.length; i++) {        var o = Textbox.Tooltips[i];        var pos = Textbox.Getpos(o);        var m = document.getElementById('__' + o.id);        if (!m) return;        m.style.left = pos.x + 'px';        m.style.top = pos.y + 'px';    }};Textbox.prototype = {    objs: [],    attr: function (o, tx, val) {        if (!val) {            return o && o.getAttribute(tx);        }        o.setAttribute(tx, val);        return o;    },    setstyle: function (ob) {        for (var o in this.Style) {            ob.style[o] = this.Style[o];        }    },    getobj: function () {        var $ = this;        $.Id = $.Properties && $.Properties.id || '__{0}'.format(Math.ceil(Math.random() * 100000));        var node;        var o = document.getElementById($.Id);        node = o ? o.parentNode : document.getElementById($.Container) ? document.getElementById($.Container) : document.body;        if (!o) {            o = document.createElement($.Type == 'textarea' ? 'textarea' : 'input');            if ($.Type != 'textarea') {                $.attr(o, 'type', $.Type);            }            for (var c in $.Properties) {                if (c == 'type') {                    continue;                }                $.attr(o, c, $.Properties[c]);            }            $.setstyle(o);            $.attr(o, 'id', $.Id);            $.attr(o, 'name', $.Id);            o.className = ($.CSS && $.CSS.Normal && !$.CSS.Normal.empty() ? $.CSS.Normal : '') + ' webUITxtBox';            node && node.appendChild(o);        }        var pos = Textbox.Getpos(o);        $.gettip($.Id, pos, node);        return o;    },    gettip: function (id, pos, ob) {        id = '__' + id;        var o = document.getElementById(id);        if (!o) {            o = document.createElement('div');            this.attr(o, 'id', id);            ob && ob.appendChild(o);        }        o.style.cssText = 'position:absolute;left:{0}px;top:{1}px;z-index:{2}'.format(pos.x, pos.y, Textbox.Zindex);        return o;    },    tooptip: {        Normal: 'Normal',        Error: 'Error',        Tooltip: 'Tooltip',        Success: 'Success'    },    tools: {        ErrorTip: '
{0}
', Normal: '
{0}
', Tooltip: '
{0}
', Success: '
{0}  
', Error: '
{0}
', width: 150 }, getverif: function (html, t, index) { var $ = this; if (!$.Verification && $.Verification.Regex.length < 1 || $.Verification == '') { return; } var width = $.Verification.Width ? $.Verification.Width : $.tools.width; width = width >= 459 ? 459 : width <= 100 ? 100 : $.tools.width; html = html.format($.Verification[index].Normal); html = html.replace("{width}", width); var d = document.getElementById('__' + $.Id); if (!d) return; d.style.display = 'block'; d.innerHTML = html; }, settooltip: function (t, html) { var $ = this; html = $.tools[t].format(html); var to = document.getElementById('__' + $.Id); if (!to) return; to.style.display = 'block'; to.innerHTML = html; var o = document.getElementById($.Id); if (!o) return; var c = o.className; var er = c.replace(/\s*(onfocus|onerror|onSuccess)/, ''); var cl = er + (t == $.tooptip.Error ? ' onerror' : t == $.tooptip.Success ? ' onSuccess' : t == $.tooptip.Tooltip ? ' onfocus' : ''); o.className = cl; }, init: function () { var $ = this; var o = $.getobj(); var pos = Textbox.Getpos(o); Textbox.Tooltips.push(o); var __ = $.Verification; if (!__ || (!__ && __.length < 1)) { o.onblur = function () { $.Callback && $.Callback.call($, o.value); } return; } $.getverif($.tools.Normal, $.tooptip.Normal, 0); Textbox.Controls.push('{
{0}:{1}}'.format($.Id, false)); Textbox.Regexs.push(__); o.onfocus = function () { var tx = this.value.trim(); for (var i = 0; i < __.length; i++) { var d = __[i]; var reg = new RegExp(d.Regex); if (!reg.test(tx)) { $.getverif($.tools.Tooltip.format(__[i].Tooltip), $.tooptip.Tooltip, i); break; } } var c = this.className; c = c.replace(/\s*(onfocus|onerror|onSuccess)/, '') + ' onfocus'; this.className = c; }; o.onblur = function () { var c = this.className; var tx = this.value.trim(); var er = c.replace(/\s*(onfocus|onerror|onSuccess)/, ''); this.className = er; $.Value = tx; var v = true; for (var i = 0; i < __.length; i++) { var d = __[i]; var reg = new RegExp(d.Regex); if (reg.test(tx)) { $.getverif($.tools.Success.format(d.Success), $.tooptip.Success, i); } else { $.getverif($.tools.Error.format(d.Error), $.tooptip.Error, i); v = false; break; } } this.className = er + (v ? ' onSuccess' : ' onerror'); if (v) { $.Callback && $.Callback.call($, tx); } }; Textbox.AddEvent(window, 'resize', Textbox.ReSize); }};Textbox.Type = { TextBox: 'text', Button: 'button', Password: 'password', Checkbox: 'checkbox', Radio: 'radio', ImageButton: 'image'};Textbox.loading = function () { Textbox.Tooltips = Textbox.Tooltips || []; var controls = []; var m = document.getElementsByTagName('input'); var ar = document.getElementsByTagName('textarea'); for (var i = 0; i < m.length; i++) { if (m[i].className.indexOf('webUITxtBox') != -1) { controls.push(m[i]); } } for (var i = 0; i < ar.length; i++) { if (ar[i].className.indexOf('webUITxtBox') != -1) { controls.push(ar[i]); } } for (var i = 0; i < controls.length; i++) { var o = controls[i]; var index = Textbox.Tooltips.indexOf(o); if (index != -1) continue; var id = o.getAttribute('id'); var vf = document.getElementById('__for' + id); var ex = vf ? vf.innerHTML : ''; ex = ex != '' ? eval('({0})'.format(ex)) : ''; var cl = o.getAttribute('Callback'); new Textbox({ Type: Textbox.Type.TextBox, Properties: { id: o.id }, Verification: ex, Callback: function (value) { } }); }};Textbox.AddEvent(window, 'load', Textbox.loading);Textbox.Regex = { Empty: /[\S]/, Email: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, //整型(包括负数) Int: /^-?[0-9]\d*$/, //整型(大于或等于0) IntPostive: /(^0$)|(^[1-9]\d*$)/, //整型(大于0) IntZeroPostive: /^([1-9]\d{0,}|0)$/, //浮点(包括负数) Float: /^(-?[1-9]\d*)|(0)\.\d+$/, //浮点(大于或等于0) FloatPostive: /(^0.0$)|(^0\.\d*[1-9]+\d*$)|(^[1-9]\d*\.\d+$)/, //浮点(大于0) (^0\.\d*[1-9]+\d*$)|(^[1-9]\d*\.\d+$) FloatZeroPostive: /^(\d+)(((\.)(\d)+))?$/, Chinese: /[\u4e00-\u9fa5]/g, EnglishChars: /[a-zA-Z]/g, Mobile: /^1(?:3[0-9]|5[0-9]|8[0-9]|4[0-9])\d{8}$/, Password: /[A-Za-z][A-Za-z0-9~!@#\$%^&\*]{5,19}/, IDCard: /[\d]{6}(19|20)*[\d]{2}((0[1-9])|(11|12))([012][\d]|(30|31))[\d]{3}[xX\d]*/, EngAndNum: /[a-zA-Z0-9]/g, URL: /^http:\/\/(?:[\w-\.]{0,255})(?:(?:\/?[^\s]{0,255}){0,255})/, EngNum: /[a-zA-Z0-9]/g, EngNumUnerline: /[a-zA-Z0-9_]*/, PhoneNumber: /(86)?(-)?(0\d{2,3})?(-)?(\d{7,8})(-)?(\d{1,5})?/, PostalCodes: /\d{6}/}

 HtmlExtension 扩展(TextboxForVerify<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression 方式)

using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using System.Text;using System.Text.RegularExpressions;using System.Web.Mvc;using System.Configuration;using System.Web.Routing;using System.Web.Helpers;using System.Reflection;namespace WebLab{    ///     /// HTML 扩展控件    ///     public static partial class HtmlExtension    {        #region 加载上传组件        ///         /// 加载组件        ///         /// HtmlHelper        /// 
public static MvcHtmlString TextboxForVerify(this HtmlHelper helper) { String basepath = DataConvert.GetString(ConfigurationManager.AppSettings["WebLab.WebUI:Base"]); basepath = basepath.LastIndexOf("/") == -1 ? basepath + "/" : basepath; String js = Helper.GetScript(String.Format("{0}Textbox/WebUI.js", basepath), helper); String style = Helper.GetStyle(String.Format("{0}Textbox/WebUI.css", basepath), helper); StringBuilder html = new StringBuilder(); html.Append(style); html.Append(js); return MvcHtmlString.Create(html.ToString()); } #endregion #region 文本框 /// /// 文本框 /// /// HtmlHelper /// Expression /// 是否允许空 ///
public static MvcHtmlString TextboxForVerify
(this HtmlHelper
helper, Expression
> expression, CommonEnum.AllowEmpty allowEmpty) { return TextboxForVerify(helper, expression, allowEmpty, CommonEnum.ValidateExpressions.Never); } ///
/// 文本框 /// ///
HtmlHelper ///
Expression ///
是否允许空 ///
默认验证类型 ///
public static MvcHtmlString TextboxForVerify
(this HtmlHelper
helper, Expression
> expression, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType) { return TextboxForVerify(helper, expression, allowEmpty, validType, null, null, null); } ///
/// 文本框 /// ///
HtmlHelper ///
Expression ///
///
验证类型 ///
验证表达式扩展 ///
public static MvcHtmlString TextboxForVerify
(this HtmlHelper
helper, Expression
> expression, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType, String[] validExpression) { return TextboxForVerify(helper, expression, allowEmpty, validType, null, validExpression, null); } ///
/// 文本框 /// ///
HtmlHelper ///
Expression ///
是否允许空 ///
默认验证类型 ///
文本框扩展属性 ///
public static MvcHtmlString TextboxForVerify
(this HtmlHelper
helper, Expression
> expression, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType, IDictionary
properties) { return TextboxForVerify(helper, expression, allowEmpty, validType, properties, null, null); } #endregion #region 带样式 ///
/// 文本框 /// ///
HtmlHelper ///
Expression ///
是否允许空 ///
样式 ///
public static MvcHtmlString TextboxForVerify
(this HtmlHelper
helper, Expression
> expression, CommonEnum.AllowEmpty allowEmpty,object style) { return TextboxForVerify(helper, expression, allowEmpty, CommonEnum.ValidateExpressions.Never, null, null, style); } ///
/// 文本框 /// ///
HtmlHelper ///
Expression ///
///
验证类型 ///
验证表达式扩展 ///
样式 ///
public static MvcHtmlString TextboxForVerify
(this HtmlHelper
helper, Expression
> expression, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType, String[] validExpression, object style) { return TextboxForVerify(helper, expression, allowEmpty, validType, null, validExpression, style); } ///
/// 文本框 /// ///
HtmlHelper ///
Expression ///
是否允许空 ///
默认验证类型 ///
文本框扩展属性 ///
样式 ///
public static MvcHtmlString TextboxForVerify
(this HtmlHelper
helper, Expression
> expression, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType, IDictionary
properties, object style) { return TextboxForVerify(helper, expression, allowEmpty, validType, properties, null, style); } #endregion #region Textbox ///
/// 文本框 /// ///
HtmlHelper ///
Expression ///
是否允许空 ///
验证类型 ///
HTML代码扩展 ///
验证表达式扩展 ///
样式 ///
public static MvcHtmlString TextboxForVerify
(this HtmlHelper
helper, Expression
> expression, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType, IDictionary
properties, String[] validExpression, object style) { String modelName = ExpressionHelper.GetExpressionText(expression); //从Lambda表达式中获取模型对应属性的名称 String value = helper.ViewData.Model == null ? "" : Helper.GetFieldValue(helper.ViewData.Model, modelName); object controlType; String __type = ""; if (properties != null) { properties.TryGetValue("type", out controlType); __type = DataConvert.GetString(controlType).ToLower(); } if (__type == "textarea") { properties.Remove("type"); } StringBuilder html = new StringBuilder(); String ex = Helper.GetTextBoxRegex(allowEmpty, validType, validExpression); html.AppendFormat("
", modelName); html.AppendFormat("
", modelName, ex); TagBuilder o = new TagBuilder(__type == "textarea" ? "textarea" : "input"); o.IdAttributeDotReplacement = "-"; o.GenerateId(modelName); o.AddCssClass("webUITxtBox"); o.MergeAttribute("name", modelName, true); o.MergeAttribute("type", "text", true); if (__type == "textarea") { o.SetInnerText(value); } else { o.MergeAttribute("value", value, true); } StringBuilder css = new StringBuilder(); if (style != null) { foreach (PropertyInfo pi in style.GetType().GetProperties()) { String key = pi.Name; string tx = pi.GetValue(style, null).ToString(); css.AppendFormat("{0}:{1};", key, tx); } } if (!String.IsNullOrEmpty(css.ToString())) { o.Attributes.Add("style", css.ToString()); } if (properties != null) { //properties.Remove("type"); o.MergeAttributes(new RouteValueDictionary(properties), true); } return MvcHtmlString.Create(o.ToString(TagRenderMode.Normal) + html.ToString()); } #endregion }}

 有些做插入操作的时候,可能为多表,所以需要一个单独的方法,侦对自定义ID,VALUE的方法扩展,如下

using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using System.Text;using System.Text.RegularExpressions;using System.Web.Mvc;using System.Web.Routing;using System.Web.Helpers;using System.Reflection;namespace WebLab{    ///     /// HTML 扩展控件    ///     public static partial class HtmlExtension    {        #region 文本框        ///         /// 文本框        ///         /// HtmlHelper        /// 控件名称        /// 
public static MvcHtmlString TextboxForVerify(this HtmlHelper helper, String name) { return TextboxForVerify(helper, name, ""); } /// /// 文本框 /// /// HtmlHelper /// 控件名称 /// 控件值 ///
public static MvcHtmlString TextboxForVerify(this HtmlHelper helper, String name, dynamic value) { return TextboxForVerify(helper, name, value, CommonEnum.AllowEmpty.True); } /// /// 文本框 /// /// HtmlHelper /// 控件名称 /// 控件值 /// 是否允许空 ///
public static MvcHtmlString TextboxForVerify(this HtmlHelper helper, String name, dynamic value, CommonEnum.AllowEmpty allowEmpty) { return TextboxForVerify(helper, name, value, allowEmpty, CommonEnum.ValidateExpressions.Never); } /// /// 文本框 /// /// HtmlHelper /// 控件名称 /// 控件值 /// 是否允许空 /// 默认验证类型 ///
public static MvcHtmlString TextboxForVerify(this HtmlHelper helper, String name, dynamic value, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType) { return TextboxForVerify(helper, name, value, allowEmpty, validType, null, null, null); } /// /// 文本框 /// /// HtmlHelper /// 控件名称 /// 控件值 /// 是否允许空 /// 默认验证类型 /// 验证表达式扩展 ///
public static MvcHtmlString TextboxForVerify(this HtmlHelper helper, String name, dynamic value, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType, String[] validExpression) { return TextboxForVerify(helper, name, value, allowEmpty, validType, null, validExpression, null); } /// /// 文本框 /// /// HtmlHelper /// 控件名称 /// 控件值 /// 是否允许空 /// 默认验证类型 /// 文本框扩展属性 ///
public static MvcHtmlString TextboxForVerify(this HtmlHelper helper, String name, dynamic value, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType, IDictionary
properties) { return TextboxForVerify(helper, name, value, allowEmpty, validType, properties, null, null); } #endregion #region 带样式 ///
/// 文本框 /// ///
///
控件名称 ///
控件值 ///
是否允许空 ///
样式 ///
public static MvcHtmlString TextboxForVerify(this HtmlHelper helper, String name, dynamic value, CommonEnum.AllowEmpty allowEmpty, object style) { return TextboxForVerify(helper, name, value, allowEmpty, CommonEnum.ValidateExpressions.Never, null, null, style); } ///
/// 文本框 /// ///
///
控件名称 ///
控件值 ///
是否允许空 ///
默认验证类型 ///
验证表达式扩展 ///
样式 ///
public static MvcHtmlString TextboxForVerify(this HtmlHelper helper, String name, dynamic value, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType, String[] validExpression, object style) { return TextboxForVerify(helper, name, value, allowEmpty, validType, null, validExpression, style); } ///
/// 文本框 /// ///
///
控件名称 ///
控件值 ///
是否允许空 ///
默认验证类型 ///
文本框扩展属性 ///
样式 ///
public static MvcHtmlString TextboxForVerify(this HtmlHelper helper, String name, dynamic value, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType, IDictionary
properties, object style) { return TextboxForVerify(helper, name, value, allowEmpty, validType, properties, null, style); } #endregion #region Textbox ///
/// 文本框(非绑定式) /// ///
///
控件名称 ///
控件值 ///
是否允许空 ///
默认验证类型 ///
文本框扩展属性 ///
验证表达式扩展 ///
样式 ///
public static MvcHtmlString TextboxForVerify(this HtmlHelper helper, String name, dynamic value, CommonEnum.AllowEmpty allowEmpty, CommonEnum.ValidateExpressions validType, IDictionary
properties, String[] validExpression, object style) { object controlType; String __type = ""; if (properties != null) { properties.TryGetValue("type", out controlType); __type = DataConvert.GetString(controlType).ToLower(); } if (__type == "textarea") { properties.Remove("type"); } StringBuilder html = new StringBuilder(); String ex = Helper.GetTextBoxRegex(allowEmpty, validType, validExpression); html.AppendFormat("
", name); html.AppendFormat("
", name, ex); TagBuilder o = new TagBuilder(__type == "textarea" ? "textarea" : "input"); o.IdAttributeDotReplacement = "-"; o.GenerateId(name); o.AddCssClass("webUITxtBox"); o.MergeAttribute("name", name, true); o.MergeAttribute("type", "text", true); if (__type == "textarea") { o.SetInnerText(value.ToString()); } else { o.MergeAttribute("value", value.ToString(), true); } StringBuilder css = new StringBuilder(); if (style != null) { foreach (PropertyInfo pi in style.GetType().GetProperties()) { String key = pi.Name; string tx = pi.GetValue(style, null).ToString(); css.AppendFormat("{0}:{1};", key, tx); } } if (!String.IsNullOrEmpty(css.ToString())) { o.Attributes.Add("style", css.ToString()); } if (properties != null) { o.MergeAttributes(new RouteValueDictionary(properties), true); } return MvcHtmlString.Create(o.ToString(TagRenderMode.Normal) + html.ToString()); } #endregion }}

 调用方法

本文使用的提交方式为JQ的AJAX提交方法,所以在_Layout.cshtml母板页中加入相关的资源

@RenderSection("Include", false)        

 实际调用方法

@model WebLab.MVCDemo.Models.CategoryEntity@{    ViewBag.Title = "Textbox";   // Model.Remark = "xxoo ";}@section Include{    @Html.TextboxForVerify()}    
主键: @Html.TextboxForVerify(m => m.Id, CommonEnum.AllowEmpty.False, CommonEnum.ValidateExpressions.Int, new Dictionary
() { { "maxlength", "11" } }, new { @width = "400px" })
分类名称: @Html.TextboxForVerify(m => m.ClassName, CommonEnum.AllowEmpty.False, CommonEnum.ValidateExpressions.Never, new Dictionary
() { { "maxlength", "50" } }, new { @width = "400px" })
详细介绍: @Html.TextboxForVerify(m => m.Remark, CommonEnum.AllowEmpty.False, CommonEnum.ValidateExpressions.Never, new Dictionary
() { { "type", "textarea" } }, new { @width = "60%", @height = "300px" })

 

 

 

源码下载地址

原创作品,如须转载,请注明出处

欢迎拍砖~~

 

转载于:https://www.cnblogs.com/weblab/archive/2012/04/08/mvc_razor_control_textbox.html

你可能感兴趣的文章
再学 GDI+[43]: 文本输出 - 获取已安装的字体列表
查看>>
nginx反向代理
查看>>
操作系统真实的虚拟内存是什么样的(一)
查看>>
hadoop、hbase、zookeeper集群搭建
查看>>
python中一切皆对象------类的基础(五)
查看>>
modprobe
查看>>
android中用ExpandableListView实现三级扩展列表
查看>>
%Error opening tftp://255.255.255.255/cisconet.cfg
查看>>
java读取excel、txt 文件内容,传到、显示到另一个页面的文本框里面。
查看>>
《从零开始学Swift》学习笔记(Day 51)——扩展构造函数
查看>>
python多线程队列安全
查看>>
[汇编语言学习笔记][第四章第一个程序的编写]
查看>>
android 打开各种文件(setDataAndType)转:
查看>>
补交:最最原始的第一次作业(当时没有选上课,所以不知道)
查看>>
Vue实例初始化的选项配置对象详解
查看>>
PLM产品技术的发展趋势 来源:e-works 作者:清软英泰 党伟升 罗先海 耿坤瑛
查看>>
vue part3.3 小案例ajax (axios) 及页面异步显示
查看>>
浅谈MVC3自定义分页
查看>>
.net中ashx文件有什么用?功能有那些,一般用在什么情况下?
查看>>
select、poll、epoll之间的区别总结[整理]【转】
查看>>