Asp. MVC5 (c): forms and HTML helper methods

Source: Internet
Author: User
Tags http post actionlink

Using the action and Method properties of the form

The action attribute tells you where the browser information is sent, so you need to include a URL address after the action Attribute. The URL address here can be relative, or it can be Absolute. The following form tag sends a search term to the Bing search page (the INPUT element is named q).

    <form action="http://www.bing.com/search">        <input name="q" type="text" />        <input type="submit" value="search" />    </form>

The method attribute tells the browser to use HTTP POST or HTTP get, by default the form sends an HTTP GET Request. below, we describe the GET method and the Post method respectively.

Get Method-request data from the specified resource
    • Get requests can be cached
    • Get requests remain in browser history
    • Get requests can be bookmark-favorites
    • Get requests should not be used when handling sensitive data
    • Get request has a length limit
    • Get requests should only be used to retrieve data
Post method-submits the data to be processed to the specified resource
    • Post requests are not cached
    • Post requests are not persisted in browser history
    • Post cannot be bookmarked
    • POST request has no requirement for data length

The following is a comparison of HTTP GET and HTTP post:

Distinguishing Items GET POST
Back Button/refresh Harmless The data will be resubmitted (the browser should tell the user that the data will be resubmitted)
Bookmark Bookmark can be bookmarked Bookmark not available for collection
Cache can be cached Cannot be cached
Encoding type application/x-www-form-urlencoded application/x-www-form-urlencoded or Multipart/form-data. Using multiple encodings for binary data
History Parameters remain in browser history Parameters are not saved in the browser history
Limits on the length of data limit, when sending data, the Get method wants to add data to the url; the length of the URL is restricted (up to 2048 characters) Unlimited
Restrictions on data types Only ASCII characters are allowed No restrictions, also allow binary data
Security Get security is poor when compared to post, because the data is exposed to the URL More secure because parameters are not saved in browser history or Web server logs
Visibility of Visible to everyone in the URL Data is not displayed in the URL

Use of Forms

below, we use the form to build an example of a query product:
Add 5 products to the example in the "asp. MVC5 (ii): controller, View and model" model section

Modify productscontroller, Add search and result methods:

    public ActionResult Search()    {        return View();    }    public ActionResult Result(string productName)    {        var products = db.Products.Where(a => a.ProductName == productName);        return View(products);    }

and add the corresponding view, the code is as follows

search.cshtml (empty template):
注意:这里我们使用了Form表单

@{    ViewBag.Title = "Search";}

result.cshtml (list template):

@model Ienumerable<myfirstmvcproject.models.product>@{viewbag.title = "Result";} 

Start the project and position the URL To/products/search with the following effect:

Enter MATEBOOKX in the text box and click the Search button to get the query Results.

With the example above, we have successfully implemented a product query function using the FORM.

HTML helper Methods

In the previous section, the use of the Html.BeginForm helper method has been involved, and the purpose of using the helper method is clear, which is to make the view encoding Easier.

Introduction to Assistive methods

Each razor view inherits the HTML attributes of their base class, the type of the HTML attribute is system.web.mvc.htmlhelper<t>, where T is a parameter of a generic type that represents the type of model passed to the VIEW. This property provides some example methods, however, most of the helper methods, such as beginform, are implemented through extension methods, and all of the htmlhelper extension methods for asp. net MVC are in the namespace System.Web.Mvc.Html.

在智能感知窗口中,左边有个向下箭头就说明这个方法是一个扩展方法。

below, we'll cover some common helper methods:

  • Html.textbox
    The TextBox helper method renders an input label of type attribute Text.
    Calling Method: @Html. TextBox ("Title", "this is Value")
    Generate HTML tag: <input id= "title" name= "title" type= "text" value= "this is value"/>
  • Html.textarea
    TextArea renders a <textarea> element that can display multiple lines of Text.
    Calling Method: @Html. TextArea ("text", "Hello! This is the Text area! ")
    Generate HTML tags: <textarea cols= "id=" "text" name= "text" rows= "2" > Hello! This is the Text area!</textarea>
  • Html.label
    The label helper method returns a <label/> element and uses the arguments of type string to determine the rendered Text.
    Calling Method: @Html. Label ("Name")
    Generate HTML tags: <label for= "Name" >Name</label>
    Name
  • Html.dropdownlist and Html.listbox
    Both the DropDownList and the ListBox helper methods return a <select/> Element. DropDownList allows for single selection, while the listbox supports multiple selections. Modify the search method in ProductsController

    public ActionResult Search(){    var products = db.Products.Single(a => a.ProductName == "Apple Pencil");    ViewBag.Products = new SelectList(db.Products.OrderBy(g => g.Price), "Id", "ProductName", products.Id);    return View();}

    and add the auxiliary method DropDownList in the corresponding view, the effect is as Follows:

    @Html.DropDownList("Products", String.Empty)
  • Html.validationmessage
    When an error occurs in a specific field in the Modelstate dictionary, you can use the Validationmessage helper method to display the appropriate error Message. Modify the search method in ProductsController

    public ActionResult Search(){    var products = db.Products.Single(a => a.ProductName == "Apple Pencil");    ViewBag.Products = new SelectList(db.Products.OrderBy(g => g.Price), "Id", "ProductName", products.Id);    ModelState.AddModelError("Title", "Support domestic products!");    return View();}

    Add the following line of code in the corresponding view to display the error message with the following effect:

    @Html.ValidationMessage("Title")

Strongly-typed helper Methods

If you are not accustomed to extracting values from view data using string literals, you can use the various strongly-typed helper methods provided by asp. With a strongly-typed helper method, you only need to pass a lambda expression for it to specify the model properties to Render. The DropDownList in our section above is an example of modifying the code in view, first, at the top of the view, enter the following code:

@model MyFirstMvcProject.Models.Product

Rewrite DropDownList using the following code:

@Html.DropDownListFor(m => m.Id, ViewBag.Products as SelectList)

The effect is as Follows:

Note that the name of a strongly typed helper method is the same as the one previously described in addition to the for Suffix. The advantage of using a strongly-typed helper method is the ability to acquire IntelliSense and Compile-time Checks.

Rendering helper Methods

Rendering helper methods can generate links to other resources in your application, or you can build reusable UI fragments called partial views.

    • Html.ActionLink and Html.routelink
      The ActionLink helper method renders a hyperlink that points to another controller. The following is an example in the Products/details view that returns the corresponding controller for the current view if no controller is specified:

      @Html.ActionLink("Back to List", "Index")

      The RouteLink helper method can accept only the route name, not the controller name and Operation Name.

      @Html.RouteLink("Back to List", new { Action = "Index"})
    • url.action, Url.routeurl and Url.content
      The URL helper method is similar to the HTML actionlink and RouteLink helper methods, but it does not return the constructed URL as HTML markup, but rather returns the URLs as Strings.
      The RouteUrl helper method, like routelink, accepts only the route name, not the controller name and Operation Name.
      The content helper method converts the relative path of an application to an absolute path.

    • Html.partial and Html.renderpartial
      Both partial and renderpartial render a partial view without using Controller,partial to return a mvchtmlstring, so you can save the result in a variable, renderpartial no value returned. Write directly to the response output Stream.

      @Html.Partial("PartialViewName")@{ Html.RenderPartial("PartialViewName"); }
    • Html.action and Html.renderaction
      Action and renderaction are similar to partial and renderpartial, but both methods use the controller to return a page, and you can add the Childactiononly feature to the controller Method. Prevent pages from being browsed directly.

Asp. MVC5 (c): forms and HTML helper methods

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.