MVC htmlhelper summary

MVC htmlhelper summary

 

Asp.Net MVC - Htmlhelper summary

HtmlHelper is a method that returns an HTML string. The returned string can be of any type. For example, you can use the HtmlHelper method to return a standard HTML tag < input > < button > < img > and so on.

You can also customize the HtmlHelper method to return some complex html to display the data.

Razor coding

First, you need to know about Razor coding

In Razor, the returned type of IHtmlString will be encoded into html, and the others are string strings.

//Controller
 string msgStr = "this is an html element: <input>";
 ViewBag.Msg = msgStr;
 ViewBag.Msg1 = new MvcHtmlString(msgStr);

Razor:

  • Html.Encode() return type is string.
  • The return type of Html.Raw() is IHtmlString.
  • The return type of MvcHtmlString.Create is mvchtmlstring inherited from IHtmlString.
  • ViewBag is a dynamic type. The type of ViewBag in Controller corresponds to that in Razor.

Briefly summarize several extension methods of HtmlHelper.

1. Helper method in view

Use @ helper in the razor page to create a custom method that can only be used in the current razor page.

@helper ListingItems(string[] items)
    {
    <ol>
    @foreach (string item in items)
    {
    <li>@item</li>
    }
    </ol>
    }
    
    <h3>Programming Languages:</h3>
    
    @ListingItems(new string[] { "C", "C++", "C#" })
    
    <h3>Book List:</h3>
    
    @ListingItems(new string[] { "How to C", "how to C++", "how to C#" })

2. Common HtmlHelper extension methods

This type of Helper can generate a variety of Hmtl controls, such as text box and checkbox.

First declare a Model

[DisplayName("student")]
public class Student
{
    public int StudentId { get; set; }
    [Display(Name="full name")]
    public string StudentName { get; set; }
    public int Age { get; set; }
    public bool isNewlyEnrolled { get; set; }
    public string Password { get; set; }
    [DisplayFormat(DataFormatString = "{0:yyyy year MM month dd day}")]
    [Display(Name ="birthday")]
    public DateTime BirthDay{get;set;}
}

1.1 TextBox

Razor:

@model Student
//Pass a null value
@Html.TextBox("StudentName", null, new { @class = "form-control" })  
//Use a string as the value
@Html.TextBox("StudentName", "this is value", new { @class = "form-control" } 
//Controller:ViewBag.StudentName="Janes";
//Get data using ViewBag
@Html.TextBox("StudentName", (string)ViewBag.StudentName, new { @class = "form-control" })  
//Controller: StudentName="Janes";
//Get data using Model
@Html.TextBox("StudentName", Model.StudentName, new { @class = "form-control" })  

Html:

<input class="form-control" id="StudentName"  name="StudentName"  type="text"  value="" />
<input class="form-control" id="StudentName"  name="StudentName"  type="text"  value="this is value" />
<input class="form-control" id="StudentName"  name="StudentName"  type="text"  value="Janes" />
<input class="form-control" id="StudentName"  name="StudentName"  type="text"  value="Janes" />

1.2 TextBoxFor

Razor:

@model Student
//Controller: StudentName="Janes";
@Html.TextBoxFor(m => m.StudentName, new { @class = "form-control" })  

Html:

<input class="form-control" id="StudentName"  name="StudentName"  type="text" value="Janes" />

The difference between TextBox and TextBoxFor:

  • @Html.TextBox is a weak type, and @ Html.TextBoxFor() is a strong type.

  • @The Html.TextBox parameter is a string, and the @ Html.TextBoxFor parameter is a lambda expression.

  • @Html.TextBox if the attribute is misspelled, the error will not be reported during compilation, but only during operation.

  • @Html.TextBoxFor will prompt errors when compiling.

2.1 TextArea

The TextArea() method is a method of type if, and the name parameter is a string. The name parameter can be the property name of the Model. It binds the specified attribute to textarea. Therefore, it automatically displays the property values of the Model in the text area and vice versa.

Razor:

@Html.TextArea("Textarea1", "val", 5, 15, new { @class = "form-control" })

Html:

<textarea class="form-control" cols="15" id="Textarea1" name="Textarea1" rows="5">val</textarea>

2.2 TextAreaFor

The TextAreaFor method is a strongly typed extension method. It generates a multiline element for the attributes in the Model specified using a lambda expression. The TextAreaFor method binds the specified Model attribute to the textarea element. Therefore, it automatically displays the value of the Model property in the text area and vice versa.

Razor:

@model Student

@Html.TextAreaFor(m => m.Description, new { @class = "form-control" })  

Html:

<textarea class="form-control" cols="20"  id="Description"  name="Description"  rows="2"></textarea>

3.1 Password

Razor:

@Html.Password("OnlinePassword")

Html:

<input id="OnlinePassword"  name="OnlinePassword"  type="password"  value="" />

3.2 PasswordFor

Razor:

@model Student
//Controller: Password="mypassword";
@Html.PasswordFor(m => m.Password)

Html:

<input id="Password" name="Password" type="password" value="mypassword" />

4.1 Hidden

Generates an input hidden field element that contains the specified name, value, and html attributes.
Razor:

@model Student
//Controller:StudentId=1;
@Html.Hidden("StudentId")

Html:

<input id="StudentId" name="StudentId" type="hidden" value="1" />

4.2 HiddenFor

Is a strongly typed extension method. It generates a hidden input element for the Model attribute specified using a lambda expression. The Hiddenfor method binds a specified Model property to a specified object property. Therefore, it automatically sets the value of the Model property to a hidden field and vice versa.

Razor:

@model Student
@Html.HiddenFor(m => m.StudentId)

Html:

<input data-val="true" id="StudentId" name="StudentId" type="hidden" value="1" />

5.1 CheckBox

Razor:

@Html.CheckBox("isNewlyEnrolled", true)

Html:

<input checked="checked" id="isNewlyEnrolled"  name="isNewlyEnrolled" type="checkbox" value="true" />

5.2 CheckBoxFor

Razor:

@model Student

@Html.CheckBoxFor(m => m.isNewlyEnrolled)

Html:

<input data-val="true"  data-val-required="The isNewlyEnrolled field is required."  id="isNewlyEnrolled"  name="isNewlyEnrolled"   type="checkbox"    value="true" />
<input name="isNewlyEnrolled" type="hidden" value="false" />

6.1 RadioButton

Razor:

Male:   @Html.RadioButton("Gender","Male")  
Female: @Html.RadioButton("Gender","Female")  

Html:

Male: <input checked="checked"  id="Gender"    name="Gender"    type="radio"     value="Male" />

Female: <input id="Gender"    name="Gender"     type="radio"     value="Female" />

6.2 RadioButtonFor

Razor:

@model Student

@Html.RadioButtonFor(m => m.Gender,"Male")
@Html.RadioButtonFor(m => m.Gender,"Female")

Html:

<input checked="checked" id="Gender" name="Gender" type="radio" value="Male" />

<input id="Gender" name="Gender" type="radio" value="Female" />

7.1 DropDownList

Razor:

@model Student

@Html.DropDownList("StudentGender",   new SelectList(Enum.GetValues(typeof(Gender))),      "Select Gender",    new { @class = "form-control" })

Html:

<select class="form-control" id="StudentGender" name="StudentGender">
    <option>Select Gender</option> 
    <option>Male</option> 
    <option>Female</option> 
</select>

7.2 DropDownListFor

Razor:

@Html.DropDownListFor(m => m.StudentGender,     new SelectList(Enum.GetValues(typeof(Gender))),    "Select Gender")

Html:

<select class="form-control" id="StudentGender" name="StudentGender">
    <option>Select Gender</option> 
    <option>Male</option> 
    <option>Female</option> 
</select>

8.1 ListBox

Razor:

@Html.ListBox("ListBox1", new MultiSelectList(new [] {"Cricket", "Chess"}))

html:

<select id="ListBox1" multiple="multiple" name="ListBox1"> <option>Cricket</option> <option>Chess</option> </select>

9.1 Display

Razor:

@model Student

@Html.Display("StudentName")

Html:

Steve

9.2 DisplayFor

Raozr:

@model Student

@Html.DisplayFor(m => m.StudentName)

Html:

Steve

10.1 Label

Razor:

@Html.Label("StudentName")
@Html.Label("StudentName","Student-Name")

Html:

<label for="StudentName">full name</label>
<label for="StudentName">Student-Name</label>

10.2 LabelFor

Razor:

@model Student

@Html.LabelFor(m => m.StudentName)

Html:

<label for="StudentName">full name</label>

11.1 Editor

This extension method is a method to generate html input elements based on data types. The Editor() or EditorFor() extension method generates html tags based on the data type of the attributes of the Model object.

data typeHtml tag
string <input type="text" >
int <input type="number" >
decimal, float <input type="text" >
boolean <input type="checkbox" >
Enum <input type="text" >
DateTime <input type="datetime" >

Razor:

StudentId:      @Html.Editor("StudentId")
Student Name:   @Html.Editor("StudentName")
Age:            @Html.Editor("Age")
Password:       @Html.Editor("Password")
isNewlyEnrolled: @Html.Editor("isNewlyEnrolled")
Gender:         @Html.Editor("Gender")
DoB:            @Html.Editor("DoB")

Html:

11.2EditorFof

Razor:

StudentId:      @Html.EditorFor(m => m.StudentId)
Student Name:   @Html.EditorFor(m => m.StudentName)
Age:            @Html.EditorFor(m => m.Age)
Password:       @Html.EditorFor(m => m.Password)
isNewlyEnrolled: @Html.EditorFor(m => m.isNewlyEnrolled)
Gender:         @Html.EditorFor(m => m.Gender)
DoB:            @Html.EditorFor(m => m.DoB)

Html:

12 Form

Razor:

  @using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { @class = "form" }))
    {
        
    }

Html:

<form action="/ControllerName/ActionName" class="form" method="post">       
     
</form>

13.1 Html.Action() executes an action and returns an html string.

13.2 Html.ActionLink() generates a hyperlink.

For example:

Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123" }, null)

return:

<a href="/somecontroller/someaction/123">link text</a>

13.3 Url.Action() returns the link address of an action

For example:

Url.Action("someaction", "somecontroller", new { id = "123" })

return:

/somecontroller/someaction/123

Custom Helper extension method

You can also create custom Helper methods by creating extension methods on the HtmlHelper class or static methods in the class.

    public static class CustomHelpers
    {
     //Submit Button Helper
     public static MvcHtmlString SubmitButton(this HtmlHelper helper, string 
     buttonText)
     {
     string str = "<input type=\"submit\" value=\"" + buttonText + "\" />";
     return new MvcHtmlString(str);
     }
     //Readonly Strongly-Typed TextBox Helper
     public static MvcHtmlString TextBoxFor<TModel, TValue>(this 
     HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>>
     expression, bool isReadonly)
     {
     MvcHtmlString html = default(MvcHtmlString);
     
     if (isReadonly)
     {
     html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
     expression, new { @class = "readOnly",
     @readonly = "read-only" });
     }
     else
     {
     html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
     expression);
     }
     return html;
     }
    }

These are some common extension methods of HtmlHelper.

 
posted @ 2017-10-24 16:43  JoeSnail  Reading (10242)   Comments (0)   edit   
 
 
Comment
Edit Preview
 
24b67464-f9ce-e011-8ee0-842b2b196315
 
  Automatic completion

My blog

 

[Ctrl+Enter shortcut submit]

 
 
 
 

Tags: ASP.NET

Posted on Thu, 11 Nov 2021 19:20:51 -0500 by Fritz.fx