2012年10月8日星期一

Asp.net下Html5新标签的扩展

Asp.net下Html5新标签的扩展

     前面一篇文章我们谈到Html5 增加的一些input attrbitue,今天让我们来在Asp.net MVC 中写一些 HtmlHelper 让其更加简单的实现。直接看下面的代码:

    #region private enum
    /// <summary>
    /// InputType enum
    /// </summary>
    private enum InputType
    {
        /// <summary>
        /// Html5 input attribute
        /// </summary>
        Color, Date, DateTime, DateTime_Local, Email, Month, Number, Range, Search, Tel, Text, Time, Url, Week
    } 
    #endregion
 
    #region Public static method
    /// <summary>
    /// Colors the specified helper.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString Color(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.Color, value, attributes);
    }
 
    /// <summary>
    /// Dates the time.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString DateTime(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.DateTime, value, attributes);
    }
 
    /// <summary>
    /// Dates the time local.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString DateTimeLocal(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.DateTime_Local, value, attributes);
    }
 
    /// <summary>
    /// Emails the specified helper.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString Email(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.Email, value, attributes);
    }
 
    /// <summary>
    /// Monthes the specified helper.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString Month(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.Month, value, attributes);
    }
 
    /// <summary>
    /// Numbers the specified helper.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString Number(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.Number, value, attributes);
    }
 
    /// <summary>
    /// Ranges the specified helper.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString Range(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.Range, value, attributes);
    }
 
    /// <summary>
    /// Searches the specified helper.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString Search(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.Search, value, attributes);
    }
 
    /// <summary>
    /// Tels the specified helper.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString Tel(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.Tel, value, attributes);
    }
 
    /// <summary>
    /// Times the specified helper.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString Time(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.Time, value, attributes);
    }
 
    /// <summary>
    /// URLs the specified helper.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString Url(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.Url, value, attributes);
    }
 
    /// <summary>
    /// Weeks the specified helper.
    /// </summary>
    /// <param name="helper">The helper.</param>
    /// <param name="name">The name.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    public static IHtmlString Week(this HtmlHelper helper, string name, object value = null, object attributes = null)
    {
        if (name.IsEmpty())
        {
            throw new ArgumentException("Value cannot be null or an empty string.", "name");
        }
        return BuildInputTag(name, InputType.Week, value, attributes);
    } 
    #endregion
 
    #region private static method
    /// <summary>
    /// Builds the input tag.
    /// </summary>
    /// <param name="name">The name.</param>
    /// <param name="inputType">Type of the input.</param>
    /// <param name="value">The value.</param>
    /// <param name="attributes">The attributes.</param>
    /// <returns>IHtmlString</returns>
    private static IHtmlString BuildInputTag(string name, InputType inputType, object value = null, object attributes = null)
    {
 
        TagBuilder tag = new TagBuilder("input");
        tag.MergeAttribute("type", GetInputTypeString(inputType));
 
        tag.MergeAttribute("name", name, replaceExisting: true);
        tag.GenerateId(name);
        if (value != null || HttpContext.Current.Request.Form[name] != null)
        {
            value = value != null ? value : HttpContext.Current.Request.Form[name];
            tag.MergeAttribute("value", value.ToString());
        }
 
        if (attributes != null)
        {
            var dictionary = attributes.GetType()
             .GetProperties()
             .ToDictionary(prop => prop.Name, prop => prop.GetValue(attributes, null));
            tag.MergeAttributes(dictionary, replaceExisting: true);
        }
        return new HtmlString(tag.ToString(TagRenderMode.SelfClosing));
 
    }
 
    /// <summary>
    /// Gets the input type string.
    /// </summary>
    /// <param name="inputType">Type of the input.</param>
    /// <returns>string</returns>
    private static string GetInputTypeString(InputType inputType)
    {
        if (!Enum.IsDefined(typeof(InputType), inputType))
        {
            inputType = InputType.Text;
        }
        return inputType.ToString().Replace('_', '-').ToLowerInvariant();
    } 
    #endregion
  上面的代码我们定义一个Enum,接着是一些扩展方法,扩展了Htmlhelper,接着在View里这样使用:

@{
    Validation.Add("email", 
        Validator.Required("You must provide an email address"),
        Validator.Regex(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$", 
        "Invalid format for an email address")
        );
    if(IsPost){
        if (!Validation.IsValid()) {
            ModelState.AddFormError("There are some errors with your submission"); 
        }
    }
}
 
<!DOCTYPE html>
 
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>My Site's Title</title>
        <style>
            body{font-family:Arial; font-size:12px; margin-left:20px;}
            div{padding-top: 5px;}
        </style>
    </head>
    <body>
        @Html.ValidationSummary(true)
        <form method="post">
            <div>Email</div>
            @Html.Email("email", attributes: new {required = "required"})
            @Html.ValidationMessage("email")
            <div>Colour</div>
            @Html.Color("colour")
            <div>Date Time</div>
            @Html.DateTime("date")
            <div>Range</div>
            @Html.Range("range")
            <div>Number</div>
            @Html.Number("number", attributes: new { min=5, max=100, step=5 })
            <div>Search</div>
            @Html.Search("search", attributes: new { placeholder = "Enter Search Term" })
            <div><input type="submit" /></div>
         </form>
    </body>
</html>


运行这个页面在适当浏览器下,当你输入的是不合法的Email,之前服务端的验证规则生效了。看下面图示:

html5-4


好了,希望这篇文章能帮助您好。对您的应用程序开发做出更好的扩展。


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog。


TAG: