asp.net-mvc
Helpers HTML
Ricerca…
introduzione
Gli helper HTML sono metodi usati per il rendering di elementi HTML in una vista. Fanno parte dello spazio dei nomi System.Web.Mvc.HtmlHelper
.
Esistono diversi tipi di helper HTML:
Helpers HTML standard : vengono utilizzati per il rendering di normali elementi HTML, ad esempio Html.TextBox()
.
Helpers HTML fortemente tipizzati : questi helper rendono gli elementi HTML basati sulle proprietà del modello, ad esempio Html.TextBoxFor()
.
Helpers HTML personalizzati : l'utente può creare un metodo di supporto personalizzato che restituisce MvcHtmlString
.
Helper HTML personalizzato: nome visualizzato
/// <summary>
/// Gets displayName from DataAnnotations attribute
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <typeparam name="TProperty"></typeparam>
/// <param name="htmlHelper"></param>
/// <param name="expression"></param>
/// <returns></returns>
public static MvcHtmlString GetDisplayName<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var value = metaData.DisplayName ?? (metaData.PropertyName ?? ExpressionHelper.GetExpressionText(expression));
return MvcHtmlString.Create(value);
}
Helper personalizzato: pulsante Invia invio
/// <summary>
/// Creates simple button
/// </summary>
/// <param name="poHelper"></param>
/// <param name="psValue"></param>
/// <returns></returns>
public static MvcHtmlString SubmitButton(this HtmlHelper poHelper, string psValue)
{
return new MvcHtmlString(string.Format("<input type=\"submit\" value=\"{0}\">", psValue));
}
Elenco esauriente di esempi HtmlHelper incluso l'output HTML
HtmlHelper.Action()
-
@Html.Action(actionName: "Index")
output: l'HTML reso da un metodo di azione chiamatoIndex()
-
@Html.Action(actionName: "Index", routeValues: new {id = 1})
output: l'HTML reso da un metodo di azione chiamatoIndex(int id)
-
@(Html.Action("Index", routeValues: new RouteValueDictionary(new Dictionary<string, object>{ {"id", 1} })))
output: l'HTML reso da un metodo di azione chiamatoIndex(int id)
-
@Html.Action(actionName: "Index", controllerName: "Home")
output: l'HTML reso da un metodo di azione chiamatoIndex()
nelHomeController
-
@Html.Action(actionName: "Index", controllerName: "Home", routeValues: new {id = 1})
output: HTML reso da un metodo di azione chiamatoIndex(int id)
nelHomeController
-
@Html.Action(actionName: "Index", controllerName: "Home", routeValues: new RouteValueDictionary(new Dictionary<string, object>{ {"id", 1} }))
output: HTML reso da un metodo di azione chiamatoIndex(int id)
nelHomeController
HtmlHelper.ActionLink()
-
@Html.ActionLink(linkText: "Click me", actionName: "Index")
output:<a href="Home/Index">Click me</a>
-
@Html.ActionLink(linkText: "Click me", actionName: "Index", routeValues: new {id = 1})
output:<a href="Home/Index/1">Click me</a>
-
@Html.ActionLink(linkText: "Click me", actionName: "Index", routeValues: new {id = 1}, htmlAttributes: new {@class = "btn btn-default", data_foo = "bar")
output:<a href="Home/Index/1" class="btn btn-default" data-foo="bar">Click me</a>
-
@Html.ActionLink()
output:<a href=""></a>
@HtmlHelper.BeginForm()
-
@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, new {id="form1",@class = "form-horizontal"}))
output:<form action="/MyController/MyAction" class="form-horizontal" id="form1" method="post">
Helpers HTML standard con i loro output HTML
-
@Html.TextBox("Name", null, new { @class = "form-control" })
output:<input class="form-control" id="Name"name="Name"type="text"value=""/>
-
@Html.TextBox("Name", "Stack Overflow", new { @class = "form-control" })
output:<input class="form-control" id="Name"name="Name"type="text" value="Stack Overflow"/>
-
@Html.TextArea("Notes", null, new { @class = "form-control" })
output:<textarea class="form-control" id="Notes" name="Notes" rows="2" cols="20"></textarea>
-
@Html.TextArea("Notes", "Please enter Notes", new { @class = "form-control" })
output:<textarea class="form-control" id="Notes" name="Notes" rows="2" cols="20" >Please enter Notes</textarea>
-
@Html.Label("Name","FirstName")
output:<label for="Name"> FirstName </label>
-
@Html.Label("Name", "FirstName", new { @class = "NameClass" })
output:<label for="Name" class="NameClass">FirstName</label>
-
@Html.Hidden("Name", "Value")
output:<input id="Name" name="Name" type="hidden" value="Value" />
-
@Html.CheckBox("isStudent", true)
output:<input checked="checked" id="isStudent" name="isStudent" type="checkbox" value="true" />
-
@Html.Password("StudentPassword")
output:<input id="StudentPassword" name="StudentPassword" type="password" value="" />
Helper personalizzato - Renderizza il pulsante radio con etichetta
public static MvcHtmlString RadioButtonLabelFor<TModel, TProperty>(this HtmlHelper<TModel> self, Expression<Func<TModel, TProperty>> expression, bool value, string labelText)
{
// Retrieve the qualified model identifier
string name = ExpressionHelper.GetExpressionText(expression);
string fullName = self.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
// Generate the base ID
TagBuilder tagBuilder = new TagBuilder("input");
tagBuilder.GenerateId(fullName);
string idAttr = tagBuilder.Attributes["id"];
// Create an ID specific to the boolean direction
idAttr = string.Format("{0}_{1}", idAttr, value);
// Create the individual HTML elements, using the generated ID
MvcHtmlString radioButton = self.RadioButtonFor(expression, value, new { id = idAttr });
MvcHtmlString label = self.Label(idAttr, labelText);
return new MvcHtmlString(radioButton.ToHtmlString() + label.ToHtmlString());
}
Esempio: @Html.RadioButtonLabelFor(m => m.IsActive, true, "Yes")
Helper personalizzato - Selezione orario
public static MvcHtmlString DatePickerFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
var sb = new StringBuilder();
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var dtpId = "dtp" + metaData.PropertyName;
var dtp = htmlHelper.TextBoxFor(expression, htmlAttributes).ToHtmlString();
sb.AppendFormat("<div class='input-group date' id='{0}'> {1} <span class='input-group-addon'><span class='glyphicon glyphicon-calendar'></span></span></div>", dtpId, dtp);
return MvcHtmlString.Create(sb.ToString());
}
Esempio:
@Html.DatePickerFor(model => model.PublishedDate, new { @class = "form-control" })
Se usi Bootstrap.v3.Datetimepicker Il tuo JavaScript è come sotto -
$('#dtpPublishedDate').datetimepicker({ format: 'MMM DD, YYYY' });
Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow