MVC View Basics

Source: Internet
Author: User
Tags actionlink

View is primarily used to render data. Because the controller and the associated service have processed the business logic and packaged the results into model entities, the view only needs to get the model and convert it to HTML

1 Select the view you want to render

In the previous article, Guestbookcontroller:

publicActionResult Create(){       returnView();}

The default rendering is views/guestbook/create.cshtml. When you call view () in a non-parametric form, the framework infers that the name of the view to render should match the name of the action. Then in the MVC pipeline, Controlleractioninvoker executes Viewresult and tells the view to render, and the framework requests viewenginecollection to locate the view to render (by default, Find the Views/<controller name> directory First, then the views/shared directory)

2View rewrite

Specify the view name to return to the view

Public ActionResult Testjson () {    return View ();} Public ActionResult testjsoncontent () {    return View ("Testjson");}

You can even specify the path to the view

Return View ("~/views/someotherdirectory/new.cshtml");

3 Passing data to view

In MVC, model objects refer to models that contain data. After the controller passes the model to the view, the view object should not do any business logic processing, only the model object to do some display logic processing.

When passing model objects, we have two choices:

1. Pass a set of weakly typed, that is, a collection of type object, in view you need to convert each member to the type we want, such as int, string, custom type, and so on.

2. Pass strongly typed objects, these types are custom to us. The strongly typed objects that we pass in the view are used directly, and the type is not required to be converted.

Pass Weakly type:

The ASP. NET MVC framework defines the ViewContext class, which, after literal translation, is the "view Context", which holds all the data about the view, where the model object is also encapsulated in this type.

Both the ViewData collection and the TempData collection are used to hold the model object. In the action of a controller, we can assign values to these two sets in the following ways:

publicActionResult <span style="color: #000000;">Create</span>() {     ViewData["hasPermission"] = true;     TempData["hasPermission"] = true;     returnView(); }

In the page, use these two collections in the following ways: @{bool haspermission= (BOOL) viewdata["Haspermission"]} @{bool haspermission= (bool) tempdata[" Haspermission "]}

Starting with MVC 3, there is a new ViewBag dynamic feature, which is mainly used to transfer values from the controller to the view, similar to the use of the viewdata[] dictionary class. It is defined as dynamic, which means that you can dynamically set/get the value, adding any number of extra fields without requiring a strong type of detection.

        Public ActionResult Create ()        {            viewbag.haspermission = true;            return View ();        }

In the page, use the following method @{bool haspermission= (bool) Viewbag.haspermission}

Strongly typed

When using razor-based views, the view inherits two types by default: System.Web.Mvc.WebViewPage or system.web.mvc.webviewpage<t>. Generics webviewpage<t> inherit from Webviewpage, but offer some unique additions that are not available in the non-generic webviewpage classes.

The following shows the skeleton member definitions for webviewpage<t>:

publicclassWebViewPage<TModel> : WebViewPage{publicnew AjaxHelper<TModel> Ajax { get; set; }publicnewHtmlHelper<TModel> Html { get; set; }publicnewTModel Model { get; }publicnewViewDataDictionary<TModel> ViewData { get; set; }}

To use a strongly typed view, first you must make sure that the controller action is correctly set to Viewdata.model. In Listing 3.4, we get all the message records, show on the list page, and pass the entire collection of personal files to the view method, which encapsulates the settings for the Viewdata.model property.

Public ActionResult Index () {    var mostrecententries = (from entry in _db. Entries                         entry. dateadded Descending                         Select entry). Take (a);    var model = Mostrecententries.tolist ();    return View (model);}

In the index view corresponding to this action, even the loosely typed webviewpage class can use the Viewdata.model property. But this property is just an object type, and we need to convert it to use it effectively. As an alternative, we can use the @model keyword to specify the type of the model.

@using Guestbook.models
@model list<guestbookentry>

The ASP. NET MVC 3 beta release adds a new @model directive to provide a cleaner and more concise way to indicate that you want to reference a strongly typed model class in a view file. All you need to do now is write @model strongmodeltype on top of your razor view file, no need to have a @inherits or specify a view EOG class

For example:

@model MvcApplication5.Models.GuestbookEntry

@model ienumerable<mvcapplication5.models.guestbookentry>

After converting to strongly typed, the data to display the response is simple, such as: @Model. Message

4 Selection of view templates

MVC provides two types of views: Aspx, Razor:

Use. ASPX "Code Fragment" is written in the way

We need to use "<%=%>" in the HTML tag to mark "Code fragment":

<%@ Page Language="C#"Inherits="System.Web.Mvc.ViewPage<DemoRC.Models.DTO.TransferModelController.StrongTypedDemoDTO>"%>...<body>    <fieldset>        <legend>Fields</legend>        <p>            UserName:             <%= Html.Encode(Model.UserName) %>        </p>        <p>            UserPassword:             <%= Html.Encode(Model.UserPassword) %>        </p>    </fieldset>    <p>        <%=Html.ActionLink("Edit", "Edit", new{ /* id=Model.PrimaryKey */}) %> |        <%=Html.ActionLink("Back to List", "Index") %>    </p></body>

Looking closely, you can see that each code fragment in the previous example requires 5 characters ("<%=%>") to indicate where the code begins and ends.

Use razor syntax to write

In razor, you only need to use an "@" character to identify the beginning of the code block, unlike the "<%%>" code fragment, Razor does not require you to explicitly indicate the end of the code block:

<ol>     <li>         @Html.LabelFor(m => m.UserName)         @Html.TextBoxFor(m => m.UserName)     </li>     <li>         @Html.LabelFor(m => m.Password)         @Html.PasswordFor(m => m.Password)     </li>     <li>         @Html.CheckBoxFor(m => m.RememberMe)         @Html.LabelFor(m => m.RememberMe, new{ @class= "checkbox"})     </li> </ol>

Personal comparison like Razor, click to see more Razor Introduction

MVC View Basics

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.