Sök…


Introduktion

HTML-hjälpare är metoder som används för att återge HTML-element i en vy. De är en del av System.Web.Mvc.HtmlHelper .

Det finns olika typer av HTML-hjälpare:

Standard HTML-hjälpare : De används för att återge normala HTML-element, t.ex. Html.TextBox() .

Starkt typade HTML-hjälpare : Dessa hjälpare återger HTML-element baserade på Html.TextBoxFor() , t.ex. Html.TextBoxFor() .

Anpassade HTML-hjälpare : Användaren kan skapa anpassad hjälpmetod som returnerar MvcHtmlString .

Anpassad HTML-hjälper - Visningsnamn

/// <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);
}

Anpassad hjälp - Render skicka knappen

/// <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));
}

Uttömmande lista över HtmlHelper-prover inklusive HTML-utdata

HtmlHelper.Action()

  • @Html.Action(actionName: "Index")
    output: HTML som ges av en handlingsmetod som heter Index()
  • @Html.Action(actionName: "Index", routeValues: new {id = 1})
    output: HTML som ges av en handlingsmetod som heter Index(int id)
  • @(Html.Action("Index", routeValues: new RouteValueDictionary(new Dictionary<string, object>{ {"id", 1} })))
    output: HTML som ges av en handlingsmetod som heter Index(int id)
  • @Html.Action(actionName: "Index", controllerName: "Home")
    output: HTML som ges av en handlingsmetod som heter Index() i HomeController
  • @Html.Action(actionName: "Index", controllerName: "Home", routeValues: new {id = 1})
    output: HTML som ges av en handlingsmetod som heter Index(int id) i HomeController
  • @Html.Action(actionName: "Index", controllerName: "Home", routeValues: new RouteValueDictionary(new Dictionary<string, object>{ {"id", 1} }))
    output: HTML som ges av en handlingsmetod som heter Index(int id) i HomeController
  • @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">

Standard HTML-hjälpare med sina HTML-utgångar

Html.TextBox ()

  • @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 ()

  • @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 ()

  • @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 ()

  • @Html.Hidden("Name", "Value")
    output: <input id="Name" name="Name" type="hidden" value="Value" />

Html.CheckBox ()

  • @Html.CheckBox("isStudent", true)
    utgång: <input checked="checked" id="isStudent" name="isStudent" type="checkbox" value="true" />

Html.Password ()

  • @Html.Password("StudentPassword")
    output: <input id="StudentPassword" name="StudentPassword" type="password" value="" />

Custom Helper - Render radioknapp med etikett

       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());
    }

Exempel: @Html.RadioButtonLabelFor(m => m.IsActive, true, "Yes")

Anpassad hjälpare - Datumväljare

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());
}

Exempel:

@Html.DatePickerFor(model => model.PublishedDate,  new { @class = "form-control" })

Om du använder Bootstrap.v3.Datetimepicker Din JavaScript är som nedan -

$('#dtpPublishedDate').datetimepicker({ format: 'MMM DD, YYYY' });


Modified text is an extract of the original Stack Overflow Documentation
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow