ASP. net mvc music store tutorial (3): View and view Model

Source: Internet
Author: User
Tags actionlink

From http://firechun.blog.163.com/blog/static/31804522201102711480936/

So far, we only return strings from the Controller action. This is a good way to understand how the controller works, but this is not the real web application you want. Program . We want a better way to generate HTML for browsers that visit our site. Using a template file, we can easily customize the HTML content sent back.

Add view Template

To use the view template, you can modify the index method of homecontroller to let it return the actionresult, as shown below ():

Public class homecontroller: Controller
{
//
// Get:/home/
Public actionresult index ()
{
Return view ();
}
}

The above modification indicates that the returned string is replaced. We use "View" to generate the returned result.

Now add an appropriate view for our project, position the cursor to the index action method, right-click, and select "add view" to go

 

 

 

The "add view" dialog box allows us to generate view template files conveniently and quickly. By default, the "add view" dialog box will pre-fill the name of the view template to match the action method using it, because we use "add view" on the right-click menu on the index Action Method of homecontroller, the "add view" dialog box uses index as the view name by default, and we do not need to change any options, click "add" button.

After clicking the "add" button, vs creates a new template in the Views \ home directory: Index. cshtml. If the directory does not exist, Vs will automatically create it.

 

The file name and folder of "index. cshtm" are very important and follow ASP. net mvc conventions. \ Views \ home matches the homecontroller controller, and the view Template Name -- index matches the Controller action method that displays the view.

Using ASP. Net MVC naming conventions to return to the view allows us to avoid displaying the name and position of the specified view template. When we write the following in homecontroller:CodeBy default, the \ views \ home \ index. cshtml view template is displayed.

Public class homecontroller: Controller
{
//
// Get:/home/
Public actionresult index ()
{
Return view ();
}
}

After pressing the "add" button in the "add view" dialog box, vs creates and opens the index. cshtml view template. The content of index. cshtml is as follows:

@{
Viewbag. Title = "Index ";
}
<H2> index </H2>

Razor is used as an example, which is more concise than ASP. Net and the web forms engine used by ASP. net mvc of earlier versions. ASP. net mvc 3 still supports the web forms view engine, but most developers think that the razor view engine is more suitable for ASP. net mvc development.

Viewbag is used for the first three rows. title sets the page title, and we will soon see how it works in more details, but now let's change the text of the view page and change the content in the <H2> label to the following:

<H2> This is the home page </H2>

Run the program. on the homepage, we can see the new text:

Most websites share the same content among multiple pages: navigation bar, footer, logo image, style reference, etc. Razor view engine automatically creates _ layout in the/views/shared folder. cshtml makes it easier to manage.

Double-click the file. The content is as follows:

<! Doctype HTML>
<HTML>
<Head>
<Title> @ viewbag. Title </title>
<Link href = "@ URL. Content ("/content/site.css ")"
Rel = "stylesheet" type = "text/CSS"/>
<SCRIPT src = "@ URL. Content ("/scripts/jquery-1.4.4.min.js ")"
Type = "text/JavaScript"> </SCRIPT>
</Head>
<Body>
@ Renderbody ()
</Body>
</Html> the content of each view is displayed by the @ renderbody () command. Any other shared content can be added to _ layout. cshtml. We want all the pages of the website to have a header linked to home and store. Simply add the code before @ renderbody. <! Doctype HTML>
<HTML>
<Head>
<Title> @ viewbag. Title </title>
<Link href = "@ URL. Content ("/content/site.css ")"
Rel = "stylesheet" type = "text/CSS"/>
<SCRIPT src = "@ URL. Content ("/scripts/jquery-1.4.4.min.js ")"
Type = "text/JavaScript"> </SCRIPT>
</Head>
<Body>
<Div id = "Header">
<H1>
ASP. net mvc music store <Ul id = "navlist">
<Li class = "first"> <a href = "/" id = "current"> Home </a> </LI>
<Li> <a href = "/store/"> store </a> </LI>
</Ul>
</Div>
@ Renderbody ()
</Body>
</Html> (reference style description, download from http://mvcmusicstore.codeplex.com Source code , All images, style scripts, and databases are in the mvcmusicstore-Assets Directory) to run the application. The new homepage is as follows:

Let's take a look at the changes:

    • Because the view template follows the standard naming conventions, the index Action Method of homecontroller finds and displays the \ views \ home \ index. aspx view template by calling "Return view.
    • By defining in \ views \ home \ index. aspx, the home page displays a simple welcome message.
    • When you use the master page, the welcome information shows a standard HTML layout.

Pass information to the view using the Model

The view template only displays hardcoded HTML content, which is insufficient for building an interesting website. To create a dynamic website, we should transfer information from the Controller action to the view template.

In Model-View-controller (Model-View-Controller) mode, a model is an object reference to the data to be presented by an application. Generally, a model object is equivalent to a table in a database, but not here.

The Controller action method that returns the actionresult can pass the model object to the view, which allows the Controller to cleanly encapsulate all required information to generate a response, pass the information to the view template and generate an appropriate HTML response. It is the easiest to understand in the Controller action, so let's get started.

First, we create some model classes to describe the categories and records of the music repository. Let's start with creating the genre class. In your project, right-click the "models" folder, select "Add-> class", and name the file genre. CS.

Add a common string attribute -- name to the created class.

Public class Genre
{
Public string name {Get; set ;}
}

Note: Here you may be surprised that {Get; set;} is the C # automatic attribute (supported by C #3.0), which makes it easy for us to define attributes without declaring fields.

Next, follow the same steps to add a record class (album. CS). It has two attributes: Title and genre.

Public class album
{
Public String title {Get; set ;}
Public Genre genre {Get; set ;}
}

Now, we can modify the storecontroller and use the view to display the model information:

We modified the details action in storecontroller to display the information of a single record. Add the using statement at the top of the storecontroller class to include the mvcmusicstore. Models namespace. In this way, the mvcmusicstore. Models. album and using sections do not need to be entered every time we use the album class:

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. Web;
Using system. Web. MVC;
Using mvcmusicstore. models;
Next, we modify the details controller action so that it returns the actionresult instead of the string. We have made the same modification to the index method of homecontroller.

Public actionresult details (int id)

Now we modify the business logic to return an album object to the view. At the end of this tutorial, we will receive data from the database. But now, let's start with "simulating data.

Public actionresult details (int id)
{
VaR album = new album {Title = "album" + id };
Return view (album );
}

(Skip the description of the VaR type variable)

Now you can create a view template that uses album to generate HTML responses. Before that, we need to generate a project so that the "add view" dialog box can know the newly created album class, select generate mvcmusicstore from the generate menu ".

After setting the supported classes, we prepare to create a view template. Right-click the details method and choose "add view" from the shortcut menu ", just like creating an image view template for homecontroller, the file \ views \ store \ details is generated by default because we create a template from storecontroller. aspx.

Different from the previous one, this time we checked "Create strong type view" and then selected the album class in the "View data class" drop-down box. The "add view" dialog box will generate a view template, and pass the album object to it.

(The following is different from the original version. Microsoft is too new. The original version already uses MVC 3. Because of the time relationship, I do not plan to use the razor Syntax of MVC 3 in our project, therefore, MVC 2 is used below, and the functions are consistent with those in the original article)

The page instruction of details. aspx contains the following code:

Inherits = "system. Web. MVC. viewpage <mvcmusicstore. Models. album>"

It indicates that this is a strong album view, which makes it easier for us to access model attributes and is supported by vs's "smart sensor.

The <H2> label displays the title attribute of album:

<H2> album: <%: model. Title %> </H2>
Note: After Entering <%:, the intelligent sensor of Vs will display that model is the default album object name, and relevant attributes and methods can be seen in the intelligent sensor.

(Note: <%: %> is the new syntax of ASP. NET 4, which is equivalent to <% = server. htmlencode () %>)

Run the application and access URL/store/details/5. We can see the details of the record:

Now we also update the Browse Action Method of storecontroller. the return value of the modification method is actionresult, and the business logic of the modification method returns a gener object to the view.

Public actionresult browse (string genre)
{
VaR genremodel = new genre {name = genre };
Return view (genremodel );
}

Right-click the Browse method and select "add view" to add a genre strong view.

Update view code:

<H2> browsing genre: <%: model. name %> </H2>

Run the application and access URL/store/browse? Genre = disco. The following page is displayed:

Finally, let's make a slightly more complex modification: Let the index action method and view of storecontroller display the list of all classes in the repository. We use the genre set instead of a single genre object.

Public actionresult index ()
{
VaR genres = new list <genre>
{
New genre {name = "Disco "},
New genre {name = "Jazz "},
New genre {name = "rock "}
};
Return view (genres );
}

Right-click the index method and select "add View", select genre as the type, and select "list" as the view content ":

Note that the page directive of index. aspx is different from the previous one. If you did not select "View content" as "list" in "add View", you can modify it as follows:

Inherits = "system. Web. MVC. viewpage <ienumerable <mvcmusicstore. Models. Genre>" change the code to the following: Browse genres <P>
Select from <%: model. Count () %> genres: </P>
<Ul>
<% Foreach (VAR genre in Model) {%>
<Li>
<%: Genre. name %> </LI>
<% }%>
</Ul> (Note: Compare the razor Syntax of MVC 3 in the original text to see the advantages of razor syntax) note that the original code generates the edit, details, and delete links for each item in the list. However, we will apply these functions later in the repository management, therefore, we replaced the automatically generated code with the simple code above. Run the program and browse/store. We can see that the quantity and list of categories are displayed.

Add links between pages /Store URL lists the names of the current category as plain text. Now let's replace these plain text with a link pointing to/store/browse URL, when we click the category name, for example, "Disco", we can navigate to/store/browse? Genre = disco URL, update the \ views \ store \ index. aspx view template and modify it to the following code: <% foreach (VAR genre in Model) {%>
<Li>
<A href = "/store/browse? Genre = <%: genre. name %> "> <%: genre. name %> </a> </LI>
<% }%>
It is okay to run, but hard encoding may cause us trouble. For example, if we want to rename the controller, we must search for all the links to the Controller in the Code and modify it. One way to choose from is to use the methods in HTML helper. The HTML helper method included in ASP. Net MVC allows us to execute various common tasks that meet such requirements from the view template. HTML. the actionlink () helper method is one of the most useful methods. It helps us easily construct HTML <A> tags, and handle annoying details, such as determining whether the URL path is properly encoded (encode ). HTML. actionlink () has several reloads, allowing us to specify the required information for the link. In our simple example, we only need to provide the action method pointed to when the link text and hyperlink are clicked. For example, we use the following code in/store/details. in aspx, create a link pointing to the index method in storecontroller: <%: HTML. actionlink ("go to the store Index", "Index") %>

Note: In the preceding example, because the current view is linked to another action of the same controller, you do not need to specify the Controller name.

To link to the Browse page, you need to pass a parameter. Here we use HTML. actionlink () to reload three parameters:

    • 1. Text of the Link -- use the type name (genre. Name)
    • 2. Controller action name -- browse
    • 3. Route parameters -- specify the parameter name and value. The parameter name is genre and the value is genre. Name.

New Code:

<% Foreach (VAR genre in Model) {%>
<Li>
<%: HTML. actionlink (genre. Name, "Browse", new {genre = genre. name}) %>
</LI>
<% }%>

Now run our project and access/store/url. We can see the category list. Each category is a hyperlink. After clicking it, we will be taken to/store/browse? Genre = [Genre] URL.

The HTML code generated by the webpage looks as follows:

<Ul>
<Li> <a href = "/store/browse? Genre = rock "> Rock </a>
</LI>
<Li> <a href = "/store/browse? Genre = jazz "> jazz </a>
</LI>
<Li> <a href = "/store/browse? Genre = Country "> country </a>
</LI>
<Li> <a href = "/store/browse? Genre = pop "> pop </a> </LI>
<Li> <a href = "/store/browse? Genre = disco "> disco </a>
</LI>
</Ul>

(Note: For the purposes and benefits of HTML. actionlink (), refer to my other article.Article: Link address issues when deploying ASP. net mvc applications)

 

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.