用于新 HTML5 输入类型的 ASP.NET MVC HTML 辅助方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3613060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:19:48  来源:igfitidea点击:

ASP.NET MVC HTML helper methods for new HTML5 input types

.netasp.net-mvchtmlhtml-helperhtml-input

提问by Drew Noakes

HTML5 appears to support a new range of input fieldsfor things such as:

HTML5 似乎支持一系列新的输入字段例如

  • Numbers
  • Email addresses
  • Colors
  • URLs
  • Numeric range (via a slider)
  • Dates
  • Search boxes
  • 数字
  • 电子邮件地址
  • 颜色
  • 网址
  • 数字范围(通过滑块)
  • 日期
  • 搜索框

Has anyone implemented HtmlHelperextension methods for ASP.NET MVC that generates these yet? It's possible to do this using an overload that accepts htmlAttributes, such as:

有没有HtmlHelper人为 ASP.NET MVC 实现了生成这些的扩展方法?可以使用接受的重载来做到这一点htmlAttributes,例如:

Html.TextBoxFor(model => model.Foo, new { type="number", min="0", max="100" })

But that's not as nice (or typesafe) as:

但这并不像以下那样好(或类型安全):

Html.NumericInputFor(model => model.Foo, min:0, max:100)

回答by Paul Hiles

Just a heads up that many of these are now incorporated into MVC4 by using the DataTypeattribute.

请注意,其中许多现在已通过使用DataType属性合并到 MVC4 中。

As of this work itemyou can use:

这个工作项目开始,您可以使用:

public class MyModel 
{
    // Becomes <input type="number" ... >
    public int ID { get; set; }

    // Becomes <input type="url" ... >
    [DataType(DataType.Url)]
    public string WebSite { get; set; }

    // Becomes <input type="email" ... >
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    // Becomes <input type="tel" ... >
    [DataType(DataType.PhoneNumber)]
    public string PhoneNumber { get; set; }

    // Becomes <input type="datetime" ... >
    [DataType(DataType.DateTime)]
    public DateTime DateTime { get; set; }

    // Becomes <input type="date" ... >
    [DataType(DataType.Date)]
    public DateTime Date { get; set; }

    // Becomes <input type="time" ... >
    [DataType(DataType.Time)]
    public DateTime Time { get; set; }
}

回答by Mauricio Scheffer

回答by dalcam

Easiest way is to simply add type="Email" as an html attribute. It overrides the default type="text". Here is an example with a html5 required validator also:

最简单的方法是简单地添加 type="Email" 作为 html 属性。它覆盖了默认的 type="text"。这是一个带有 html5 必需验证器的示例:

@Html.TextBox("txtEmail", "", new {placeholder = "email...", @type="email", @required = ""})

回答by RPAlbert

What i don't like about DataTypesAttributes is that u have to use EditorForin the view. Then, you can't use htmlAttributesto decorate your tag. There are other solutions but i prefer this way.

我不喜欢DataTypes属性的一点是你必须在视图中使用EditorFor。然后,您不能使用htmlAttributes来装饰您的标签。还有其他解决方案,但我更喜欢这种方式。

In this example i only extended the signature i use the most.

在这个例子中,我只扩展了我最常用的签名。

So in the class:

所以在课堂上:

using System.Linq.Expressions;
namespace System.Web.Mvc.Html
{
    public static class HtmlExtensions
    {
        public static MvcHtmlString EmailFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, Object htmlAttributes)
        {
            MvcHtmlString emailfor = html.TextBoxFor(expression, htmlAttributes);
            return new MvcHtmlString(emailfor.ToHtmlString().Replace("type=\"text\"", "type=\"email\""));
        }
    }
}

As you see i just changed the type="text" for type="email" and then i can use in my view:

如您所见,我刚刚更改了 type="email" 的 type="text",然后我可以在我的视图中使用:

    <div class="form-group">            
        @Html.LabelFor(m => m.Email, new { @class = "col-lg-2 control-label" })
        <div class="col-lg-10">
            @Html.EmailFor(m => m.Email, new { @class = "form-control", placeholder = "Email" })
            @Html.ValidationMessageFor(m => m.Email)                                 
        </div>            
    </div>

And the html source gives:

并且 html 源代码给出:

<div class="form-group">            
    <label class="col-lg-2 control-label" for="Email">Email</label>
    <div class="col-lg-10">
        <input class="form-control" data-val="true" data-val-required="The Email field is required." id="Email" name="Email" placeholder="Email" type="email" value="" />
        <span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>                                 
    </div>            
</div> 

回答by Phillip Wells

Love it when can drive this type of stuff off the model!! I decorated my models with [DataType(DataType.PhoneNumber)], and all but one worked.

喜欢它什么时候可以把这种东西从模型上赶下来!!我用 装饰了我的模型[DataType(DataType.PhoneNumber)],除了一个之外,其他所有模型 都有效。

I realized the hard way that @Html.TextBoxFordoesn't render the type="<HTML5 type>"but @Html.EditorFordoes. Makes sense I guess now that I think about it, but posting this to maybe save others the frustrating few minutes that I just lost;)

我意识到@Html.TextBoxFor不呈现type="<HTML5 type>"@Html.EditorFor确实如此的艰难方式。我想现在我想是有道理的,但是张贴这个可能是为了节省其他人我刚刚失去的令人沮丧的几分钟;)

回答by Ben

I found my self wanting the number spinner you get when using <input type='number' />from an HtmlHelper, and ended up solving it my self.

我发现我自己想要使用<input type='number' />HtmlHelper时获得的数字微调器,最终我自己解决了这个问题。

In a similar fashion to RPAlbert's Html.EmailFor answer above, I started off using the normal Html.TextBoxFor, but then I used LinqToXml to modify the HTML rather than just using a string replace.

以与上面 RPAlbert 的 Html.EmailFor 答案类似的方式,我开始使用普通的 Html.TextBoxFor,但后来我使用 LinqToXml 来修改 HTML,而不仅仅是使用字符串替换。

The advantage of starting with the Html.TextBoxFor is that you can use of all the client side validation stuff that MVC does for you. In this case I am using the values from the data-val-rangeattributes to set the min/max attributes needed to constrain the spinner.

从 Html.TextBoxFor 开始的优点是您可以使用 MVC 为您所做的所有客户端验证内容。在这种情况下,我使用data-val-range属性中的值来设置约束微调器所需的最小/最大属性。

public static HtmlString SpinnerFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
    XDocument _xml = XDocument.Parse(html.TextBoxFor(expression, htmlAttributes).ToString());
    XElement _element = _xml.Element("input");

    if (_element != null)
    {
        _element.SetAttributeValue("type", "number");

        if (_element.Attribute("data-val-range-max") != null) 
            _element.SetAttributeValue("max", _element.Attribute("data-val-range-max").Value);

        if (_element.Attribute("data-val-range-min") != null) 
            _element.SetAttributeValue("min", _element.Attribute("data-val-range-min").Value);
    }

    return new HtmlString(_xml.ToString());
}

You would then use it as you would any other HtmlHelper in your views:

然后,您可以像在视图中使用任何其他 HtmlHelper 一样使用它:

@Html.SpinnerFor(model => model.SomeNumber, new { htmlAttribute1 = "SomeValue" })

@Html.SpinnerFor(model => model.SomeNumber, new { htmlAttribute1 = "SomeValue" })

This was my implementation of it anyway, from you question I can see that you wanted:

无论如何,这是我的实现,从你的问题我可以看出你想要:

@Html.NumericInputFor(model => model.Foo, min:0, max:100)

@Html.NumericInputFor(model => model.Foo, min:0, max:100)

It would be very simple to tweak my method to do this as follows:

调整我的方法来执行此操作非常简单,如下所示:

public static HtmlString NumericInputFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, int min, int max)
{
    XDocument _xml = XDocument.Parse(html.TextBoxFor(expression, htmlAttributes).ToString());
    XElement _element = _xml.Element("input");

    if (_element != null)
    {
        _element.SetAttributeValue("type", "number");
        _element.SetAttributeValue("min", min);
        _element.SetAttributeValue("max", max);
    }

    return new HtmlString(_xml.ToString());
}

Basically all I have done is to rename it and provide min/max as arguments rather than getting them from DataAnnotation attributes.

基本上我所做的就是重命名它并提供 min/max 作为参数,而不是从 DataAnnotation 属性中获取它们。

I hope that helps!

我希望这有帮助!