ASP. NET MVC View

Source: Internet
Author: User

The view view responsibility is to provide the user with an interface. Responsible for generating the format interface that is prepared to be provided to the user based on the provided model data.

Support for multiple view engines (Razor and ASPX view engines are officially given by default, but also support other n view engines, even you can write a set of view engines)

Data transfer between view and action (pre-background data transfer)

Weak type viewdata[""]

Dynamic type ViewBag//dynamic

Dynamic type model
Backstage: Return View (data); Deposit Viewdata.model
Front Desk: Model//actually is Webviewpage.model

@using namespaces

Strongly typed view

        Control  Action public        actionresult Index ()        {            return View (new User {UserName = "Guo Jing"});// Viewdata.model Property        }

Index.cshtml

@model MvcApplication.Models.User

<div> @Model .username</div>
Razor View engine syntax

Razor provides a streamlined syntax for the view, minimizing syntax and extra strings

    • Razor enables smooth switching between code and markup by understanding the structure of the tag.
    • @ Core conversion character, which is used to mark-code the conversion string.

Context A:

@{    string Schoolname= "Hunan first Normal School";}

Context B:

Razor engine identification @ and <>html</>

Razor syntax

Razor expression automatically uses HTML encoding

If the source Html code is first exported to the browser, use System.Web.IHtmlString: @Html. Raw ("<p>zouyujie</p>")

Output result Zouyujuie

HTML source

JS string encoding

<script>     alert (' @Ajax. Javascriptstringencode (viewbag.username) ');</script>

Results:

@ code block

     @{  string s = "Zouyujie";         int age =26;      }     @{html.renderpartial ("Testpartial");} Call no return value method

Note:@* ... *@. ....

call the generic method:@ (html.somemethod<user> ());

Mix code with text:

@if (1==1) {     <text> I want to output text here! </text>     @: I want to output text here!    }

@ escape: @@

manipulating web built-in objects:@Request. RawUrl @Response. Write

The @ scope is mixed with HTML tags:

     @{          string username= "Liu Bang";          
}

Output non-escaped HTML code at the @ scope

1. Using a string to describe the output

      @{           string strhtm= "<p> Hello ~</p>";           @strHtml       }

2. Using the HtmlHelper output

@{    @Html. Raw ("<p> aha ~</p>");  }

3. Using the Htmlstring class output

     @{          htmlstring htm =new htmlstring ("<p> haha </p>");          @htm      }

4. Using the mvchtmlstring output

     @{         var strhtml=mvchtmlstring.create ("<p> haha ~</p>");         @strHtml      }

Data type conversions

Use as .... () method conversion, such as @ ("120". Asint ())

Numeric type judgment

Using the Isint () method, such as @ (Strage.isint ()? " Yes ":" No ")

Path conversion

Using the Href () method, such as: @Href ("~/home/index");

The using system.web.webpages;//internally expands many as for string. Method

HtmlHelper reuse: Equivalent to defining a method in a view

@helper List (list<string> dogs) {    <ul>        @foreach (string s in dogs)        {            <li>@s</li >        }    </ul>    @List (New list<string> () {"Ruiky", "Lisa", "Lucy"})
Razor Layout – Overall view template

Apply the overall template view

[Email protected] ()//placeholder in the template page

[Email protected] {

Layout = "~/views/shared/sitelayout.cshtml";

view.title= "User List";

}

<p> child pages All HTML code is replaced with the @renderbody () at the template page </p>

Apply the overall view template-Multiple placeholders

3. Template page Multiple sections:

<footer> @RenderSection ("footer") </footer>

Child page Definition node:

    @section footer{           <b> We're going to join in! </b>     }

The template page determines whether it is a layout section method, issectiondeined

  @if (issectiondefined ("Footer")) {         @RenderSection ("Footer");   } else   {         <b> "sub-page" does not have footer~</b>   }

Razor Layout –viewstart

Each sub-page specifies a layout using one layout. If multiple views are used in the same layout, redundancy is generated and maintenance headaches are changed.

_viewstart.cshtml to resolve this issue

This file code takes precedence over any view code execution in the same directory and subdirectory

Automatically added _viewstart.cshtml in the View directory

   @{          Layout = "~/views/shared/_layout.cshtml";    

With it, you can add the same view layout to all the views under a folder

Because this file code takes precedence over any view, any view can override the Layout property to specify the template layout page that you want.

Razor Layout – Distribution View

The action method can return a partial view in partialviewresult form through the Partialview method
Typically used in AJAX request part code
Controller

        Public ActionResult partialviewtest ()        {            viewdata["Msg"] = "Hello world!";            return Partialview ();        }

Partialviewtest.cshtml

<div> @ViewData ["MSG"] </div>

Index.cshtml

<div id= "Divtest" >     @{html.renderaction ("Partialviewtest");} </div>

View Engine

"Just an angle bracket generator."

This figure is just to emphasize:
1. Where the view engine works, it immediately follows the action method execution.
Its purpose is to get the data passed from the controller and generate the formatted output.
2. The controller does not render the view, it simply prepares the data (Model) and decides which view to invoke by Viewresult the instance.
View Engine Interface Iviewengine

Public interface Iviewengine {        viewengineresult findpartialview (ControllerContext controllercontext, string Partialviewname, bool usecache);        Viewengineresult Findview (ControllerContext controllercontext, String viewName, String mastername, bool usecache);        void Releaseview (ControllerContext controllercontext, IView view);
}

Viewengineresult Property

Other View engines: spart,nhaml,brail,stringtemplate,nvelocity

View IView

Public interface IView {        void Render (ViewContext viewcontext, TextWriter writer);}

The "secret" of the MVC View

In fact, our cshtml view page, when accessed, also compiled into a page class, inherited from the:webviewpage<t>

On the view page, add code

<div>@{response.write (this. GetType (). assembly.location);} </div>

Running result: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP. files\root\c8628c1b\abb1511c\app_web_ Ceor5kns.dll

View this DLL with the Reflector anti-compile tool

All the code in the Cshtml page is compiled into the Excute method of this class.

Catalog: ASP. NET MVC4 get started to Master Series catalog summary

ASP. NET MVC View

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.