MVC Learning Series-form data submission

Source: Internet
Author: User
Tags allkeys form post list of attributes naming convention

In an ASP. NET MVC Project, view is responsible for displaying the page, collecting the data, showing the data from the Controller's action, and submitting the collected data to the Controller's action. The data here may be the underlying type, or model, or part of the model, or a collection such as List or dictionary.

There are several ways to count the actions that are passed from view to the controller:

1.RouteData (route data in the URL),

2.QueryString (query parameters for HTTP GET, such as page=2),

3.Forms (data from Form POST),

4. Or JSON data for Ajax interaction.

In the Controller's action, we often want to get the data that these view passes, and it's best to bind to the type of action you want. These types may be the underlying type parameters of the action, or need to update the model, or only part of the model, or the structure of some collections such as List or dictionary.

Here are a few ways to get the data from view delivery

Method 1.

Public ActionResult Create () {    Recipe Recipe = new Recipe ();    Recipe. Name = request.form["Name"];    // ...   return View ();}
Method 2.
Public ActionResult Create (formcollectionvalues) {    Recipe Recipe = new Recipe ();    Recipe. Name = values["Name"];           // ...   return View ();}
Method 3.

The ASP. NET MVC built-in functionality (Defaultmodelbinder) enables simple types, complex types, collection types, and automatic binding of dictionary types.

1. Simple Type

We refer to the following book class as a simple type:

<pre name= "code" class= "CSharp" ><pre name= "code" class= "CSharp" >public class book    {public        int BookId {get; set;}        public string BookName {get; set;}        public string Author {get; set;}        Public DateTime publisheddate {get; set;}    } Public ActionResult Create {//to does//insert book to            Database            return redirecttoaction ("Index" );        }

The corresponding view page code is as follows:

<div>        <%using (Html.BeginForm ("Create", "book")} {%>        <div> book            Name: <%= Html.textbox ("BookName")%>        </div>        <div>            Author: <%=html.textbox ("Author")%>        </div>        <div>            Published Date: <%=html.textbox ("Publisheddate")%>        </div>        <div>            <input type= "Submit" id= "submit" name= "submit" value= "Submit"/>        </div>        <%}%>    </div>

Note the name of the TextBox must be a propertyname of the corresponding binding type (case insensitive). This way, when the page form is submit, we can get the automatically bound book object in the Bookcontroller "Create" action. Here, ASP. NET MVC also supports the case where a variable name prefix is added to the textbox's name:
<pre name= "code" class= "HTML" ><pre name= "code" class= "HTML" ><div>        <%using (Html.BeginForm ( ' Create ', ' book ') {%>        <div> book            Name: <%=html.textbox. BookName ")%>        </div>        <div>            Author: <%=html.textbox (" book. Author ")%>        </div>        <div>            Published Date: <%=html.textbox (" book. Publisheddate ")%>        </div>        <div>            <input type=" Submit "id=" submit "name=" Submit " Value= "Submit"/>        </div>        <%}%>    </div>

2. Complex types

Now make some changes to the book class and introduce the author class

public class book    {public        int BookId {get; set;}        public string BookName {get; set;}        Public Author Author {get; set;}        Public DateTime publisheddate {get; set;}    }    public class Author {public        int Authorid {get; set;}        public string AuthorName {get; set;}        public string Nation {get; set;}    }

The code for the corresponding view page is as follows:

<div>        <%using (Html.BeginForm ("Create", "book")} {%>        <div> book            Name: <%= Html.textbox ("BookName")%>        </div>        <div>            Published Date: <%=html.textbox (" Publisheddate ")%>        </div>        <div>            Author ' s Name: <%=html.textbox (" Author.authorname ") %>        </div>        <div>            Author ' s Nation: <%=html.textbox ("Author.nation")%>        < /div>        <div>            <input type= "Submit" id= "submit" name= "submit" value= "Submit"/>        </div >        <%}%>    </div>

3. Collection type

To avoid complications, we use back the original simple book type

<span style= "FONT-SIZE:12PX;" >public class book    {public        int BookId {get; set;}        public string BookName {get; set;}        public string Author {get; set;}        Public DateTime publisheddate {get; set;}    } </span><span style= "FONT-SIZE:14PX;" ></span>

Now, change the Bookcontroller "Create" action to receive the ilist<book> parameter:

Public ActionResult Create (Ilist<book> books) {            //to does            //insert book into Database            return Redirecttoaction ("Index");        }

Use the following naming convention in view to automatically bind the ilist<book> type

<div>        <%using (Html.BeginForm ("Create", "book")} {%>        <div> book            Name: <%= Html.textbox ("Books[0"). BookName ")%>        </div>        <div>            Published Date: <%=html.textbox (" Books[0 "). Publisheddate ")%>        </div>        <div>            Author ' s Name: <%=html.textbox (" Books[0 "). Author ")%>        </div>        <div> book            Name: <%=html.textbox (" Books[1 "). BookName ")%>        </div>        <div>            Published Date: <%=html.textbox (" Books[1 "). Publisheddate ")%>        </div>        <div>            Author ' s Name: <%=html.textbox (" Books[1 "). Author ")%>        </div>        <div>            <input type=" Submit "id=" submit "name=" Submit "value=" Submit "/>        </div>        <%}%>    </div>

You can see the following rule: The variable name "books" of the action plus the brackets and indexes as prefixes, the index must start at 0 and must be contiguous.
with this naming convention, you can bind any collection type: Ilist<book>, Icollection<book>, Ienumerable<book>, List<book>, book [] and so on.

4. Dictionary type

Still use the simple book type as an example, now change the "Create" action to receive the idictionary<book> type

Public ActionResult Create (idictionary<string, book> Books) {            //to does            //insert book into Database            Return redirecttoaction ("Index");        }
The code for the corresponding view page is as follows:

<pre name= "code" class= "HTML" ><pre name= "code" class= "HTML" ><pre name= "code" class= "HTML" ><div > <%using (Html.BeginForm ("Create", "book")) {%> <div> book SN: <%=html.textbo X ("Books[0"). Key ")%> </div> <div> book Name: <%=html.textbox (" Books[0 "). Value.bookname ")%> </div> <div> Published Date: <%=html.textbox (" Books[0 "). Value.publisheddate ")%> </div> <div> Author ' s Name: <%=html.textbox (" books[0].v Alue. Author ")%> </div> <div> book SN: <%=html.textbox (" Books[1 "). Key ")%> </div> <div> book Name: <%=html.textbox (" Books[1 "). Value.bookname ")%> </div> <div> Published Date: <%=html.textbox (" Books[1 "). Value.publisheddate ")%> </div> <div> Author 'S Name: <%=html.textbox ("Books[1"). Value.author ")%> </div> <div> <input type=" Submit "id=" submit "name=" Submit "va Lue= "Submit"/> </div> <%}%> </div>

As can be seen, for the idictioinary<book> type, on the naming rules, compared to the collection type, more "Key" and "Value" word. In addition, this rule applies to cases where the action parameter type is dictionary<book>. simple types, complex types, collection types, and dictionary types can also be mixed, and the bound data source is not limited to the expression data submitted by the form, or it can be routedata (route data in the URL), QueryString (HTTP GET query parameters such as? page=2), or JSON data that Ajax interacts with.

Therefore, as long as we follow certain naming rules, flexible use of defaultmodelbinder can easily implement various types of automatic binding.

5.tryupdatemodel/updatemodel

A typical use case that is often encountered in MVC is that the view updates the corresponding model with the From or AJAX submission data, or updates part of the model, and needs to check that the submitted data is valid for the model's data constraints. this time TryUpdateModel will be useful, it can be set to update the Model property list (whitelist) or to exclude the list of attributes (blacklist) to see the update related models of all the properties:

Publicactionresult Edit (int ID, formcollection collection) {    var olddata = _r.getsingledata (ID);     if (TryUpdateModel (OldData, collection. AllKeys))    {        _r.save ();    }}

To update the model property except Id,name:

Publicactionresult Edit (Guid ID, formcollection collection) {    var olddata = _r.getsingledata (ID);     if (TryUpdateModel (OldData, "", collection. allkeys,newstring[]{"ID", "Name"}))    {        _r.save ();}    } Publicactionresult Save () {    customer customer =newcustomer ();   Try   {        Updatemodel (customer,new[] {"Name", "Email",           "Phone", "Deposit"});       Return Redirecttoaction ("...");   catch (InvalidOperationException)    {       Returnview (customer);    }}
Updatemodel and TryUpdateModel have many overloaded forms for a variety of flexible applications, and it will automatically check that the model binds the data for errors, and if any errors are automatically added to the modelstate and prompted on the page.
Reference: Https://msdn.microsoft.com/zh-cn/library/system.web.mvc.controller_methods (v=vs.118). aspx

MVC Learning Series-form data submission

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.