ASP. NET MVC 4.0 learning 6-model Binding

Source: Internet
Author: User

One, Viewdata,viewbag with TempData

In the ASP. NET MVC structure, access to the Viewdata,viewbag and TempData and view pages in the controller is inherited, and is suitable for a small amount of information to pass.

1.1 ViewBag

ViewBag can be dynamic and we see how viewbag is used in the new project:

Controller value: viewbag.title= in "Home" view @ViewBag. Title

1.2 ViewData

Controller value: viewdata["message"]= "This is ViewData value";

View page value: @ViewData ["Message"]

1.3 TempData

Unlike Viewbag,viewdata, TempData presets Store the information in the session,

The life cycle exists throughout the request, and can be transferred between controller and Controller.

   PublicActionResult Index () {//ViewDataviewdata["Viewdatavalue"] ="This is ViewData Value"; //TempDatatempdata["Tempdatavalue"] ="This is tempdata Value"; //ViewBagViewbag.message ="Modify this to start your ASP. NET MVC application. "; returnView (); }
View Code
class="title">                "viewdatavalue"]"tempdatavalue"]
View Code

Two, Model Connection (Model Binding)

in ASP. NET MVC, the model Binding is used to enable the controller to access the information in the view.

2.1 Simple Model Connection

In the example below, the view page has a text box with the ID content, and the corresponding action has the same name as the content, So when the action is executed, the program passes through the Defaultmodelbinder category to the same name in the action with the information passed to the view page.

View:

@using (Html.BeginForm ()) {<div> @Html. Label ("Please enter the content contents:") <input type="text"/name="content"></div> <div> @Html. Label ("The content you enter is:") @ViewData ["content"]</div> <input type="Submit"Value="Submit"/>}

Action:

         Public ActionResult testaction (string  content)        {            viewdata["content" ] = content;             return View ();        }

Let's take a look at this, click Submit, and then pass the simple digital connection model to the values in the Content text box to Testaction's parameters, and then pass through the viewdata["Content" to get the value out.

2.2 FormCollection

In addition to the simple model connection for the view page, ASP. NET MVC can also access the entire client page through FormCollection.

Add formcollection to the action to get the form information.

View:

@{Viewbag.title ="Testaction";} @using (Html.BeginForm ()) {<div> @Html. Label ( " Please input content: ") < Input Type= "text" Name= "content" > </div> <div> @Html. Label ( you enter the content:  ") @ViewData [" content  "]</div> <input type=" submit"  submit  "/>       
View Code

Action:

  formcollection public         actionresult testaction (formcollection form)        {            viewdata[" content"] = form["content"return View ();       
View Code

2.3 Complex Model Connection

1, we add the Testformmodel category, the definition of three

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.ComponentModel.DataAnnotations;namespacemvcapplication3.models{ Public classTestformmodel { Public stringContent {Get;Set; }  Public stringUserID {Get;Set; }  Public intAge {Get;Set; } }}
View Code

The 2,action parameters are changed to Testformmodel to receive the view page's passed form form,

As long as the linked fields bit name in the form table and the one in the model category are applied, the receiving action can be completed.

View:

@{Viewbag.title="Testform";}@using (Html.BeginForm ()) {<div>@Html. Label ("Please enter content:")        <input name="content"Type="text"/> </div> <div> @Html. Label ("Please enter a userid:") <input Name="UserID"Type="text"/></div> <input type="Submit"Value="Submit"/> <div>your submission is: content= @ViewData ["Content"]        <br/>UserID= @ViewData ["UserID"]    </div>}
View Code

Action, remember to add a reference model

    // Complex model Connections         Public actionresult testform (testformmodel form)        {            viewdata["Content"] = form. Content;            viewdata["UserID"] = form. UserID;             return View ();        }
View Code

The value of the 3,view page is passed to the controller after the form form is passed through the model format, and is read through ViewData.

We will be able to see the passing of the numbers:

2.4 judge the model to prove the outcome

In the previous example, we can see that the form form in view is a one-to-one response to the nature of the model, and we are able to put the evidence part in the model.

When the controller is connected to the model, the program automatically processes the work of the model, and the results are stored with the Modelstate object.

Now that we have updated the model's nature, the front plus [Required] indicates that it has to have a value when modelstate. Isvalid==true

Model:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.ComponentModel.DataAnnotations;namespacemvcapplication3.models{ Public classTestformmodel {[Required] Public stringContent {Get;Set; } [Required] Public stringUserID {Get;Set; } [Required] Public intAge {Get;Set; } }}

View:

@{Viewbag.title="Testform";}@using (Html.BeginForm ()) {<div>@Html. Label ("Please enter content:")        <input name="content"Type="text"/> </div> <div> @Html. Label ("Please enter a userid:") <input Name="UserID"Type="text"/></div> <input type="Submit"Value="Submit"/> <div>your submission is: content= @ViewData ["Content"]        <br/>UserID= @ViewData ["UserID"]    </div> <div>model in the state of the evidence: @ViewData ["Message"]</div>}

Action: When both text boxes enter values, the success of the experiment failed

   ////model Validation         Publicactionresult testform (Testformmodel form) {if(modelstate.isvalid) {//data in model conforms to specificationviewdata["Message"] ="The experience proves that through"; viewdata["Content"] =form.                Content; viewdata["UserID"] =form.            UserID; }            Else{viewdata["Message"] ="Experience Failure"; }            returnView (); }

ASP. NET MVC 4.0 learning 6-model Binding

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.