ASP.NET metody MVC HTML helper dla nowych typów wejściowych HTML5
HTML5 wydaje się obsługiwać nowy zakres pól wejściowych dla rzeczy takich jak :
- liczby
- adresy E-Mail
- Colors
- Url
- zakres liczbowy (poprzez suwak)
- daty
- pola wyszukiwania
Czy ktoś zaimplementował HtmlHelper
metody rozszerzenia dla ASP.NET MVC, który je już generuje? Można to zrobić za pomocą przeciążenia przyjmującego htmlAttributes
, np.:
Html.TextBoxFor(model => model.Foo, new { type="number", min="0", max="100" })
Ale to nie jest takie miłe. as:
Html.NumericInputFor(model => model.Foo, min:0, max:100)
6 answers
Uwaga, że wiele z nich jest teraz włączanych do MVC4 za pomocą DataType
atrybut.
Od tego elementu pracy możesz użyć:
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; }
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-10 07:54:02
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-31 20:50:55
Co nie podoba mi się wDataTypes atrybuty jest to, że musisz użyćEditorFor w widoku. Następnie nie możesz użyć htmlAttributes do dekoracji swojego tagu. Są inne rozwiązania, ale wolę ten sposób.
W tym przykładzie rozszerzyłem tylko podpis, którego używam najczęściej.
Więc w klasie:
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\""));
}
}
}
Jak widzisz właśnie zmieniłem type= "text" dla type = "email" i wtedy mogę użyć w moim widoku:
<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>
I źródło html daje:
<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>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-18 00:41:47
Uwielbiam, kiedy można wypędzić tego typu rzeczy z modelu!! Udekorowałam moje modelki [DataType(DataType.PhoneNumber)]
i wszystkie oprócz jednego działały.
Zdałem sobie sprawę z tego, że @Html.TextBoxFor
nie renderuje type="<HTML5 type>"
, ale @Html.EditorFor
robi. Wydaje mi się, że teraz myślę o tym, ale publikowanie tego może uratować innym frustrujące kilka minut, które właśnie straciłem;)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-05 14:21:21
Najprostszym sposobem jest dodanie type = "Email" jako atrybutu html. Nadpisuje domyślny typ = "tekst". Oto przykład z walidatorem wymaganym przez html5:
@Html.TextBox("txtEmail", "", new {placeholder = "email...", @type="email", @required = ""})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-29 00:42:05
Znalazłem moje ja chcąc numer spinner można dostać podczas korzystania <input type='number' />
z HtmlHelper, i skończyło się rozwiązując go moje ja.
W podobny sposób jak Html Rpalberta.E-maildla odpowiedzi powyżej, zacząłem używać normalnego Html.TextBoxFor, ale potem użyłem LinqToXml do modyfikacji HTML, a nie tylko za pomocą string replace.
Zaletą rozpoczynania od Html.TextBoxFor jest to, że można użyć wszystkich rzeczy walidacji po stronie klienta, które MVC robi dla Ciebie. W tym przypadku używam wartości z atrybutów data-val-range
, aby ustawić atrybuty min / max potrzebne do ograniczenia wirnika.
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());
}
Użyłbyś go tak, jak każdy inny HtmlHelper w swoich poglądach:
@Html.SpinnerFor(model => model.SomeNumber, new { htmlAttribute1 = "SomeValue" })
To i tak była moja realizacja, z twojego pytania widzę, że chciałeś: {]}
@Html.NumericInputFor(model => model.Foo, min:0, max:100)
Byłoby bardzo proste, aby dostosować moją metodę, aby zrobić to w następujący sposób:
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());
}
W zasadzie wszystko, co zrobiłem, to zmienić nazwę i podać min / max jako argumenty zamiast pobierać je z atrybutów DataAnnotation.
Mam nadzieję, że to pomoże!Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-01 15:36:22