ASP. net mvc Framework experience (4): Controller

Source: Internet
Author: User
Overview

In MVC, the Controller is used to process and respond to user interactions. It selects the View to be used for display and the View data to be transmitted to the View. ASP. net mvc Framework provides two types: IController interface and Controller base class, in which Controller provides some common processing in MVC, for example, locate and execute the correct action, assign values to the action method parameters, handle errors during execution, and provide the default WebFormViewFactory page. IController only provides a controller interface. If you want to customize a controller, You can implement IController. Its definition is as follows:

public interface IController{    void Execute(ControllerContext controllerContext);}

Define controllers and actions

In the previous three examples, we have already defined the Controller, as long as it inherits from the Controller:

public class BlogController : Controller{    [ControllerAction]    public void Index()    {        BlogRepository repository = new BlogRepository();        List<Post> posts = repository.GetAll();        RenderView("Index", posts);    }    [ControllerAction]    public void New()    {         RenderView("New");    }}
Using the ControllerAction feature to specify a method as action, the definition of ControllerAction is very simple:
[AttributeUsage(AttributeTargets.Method)]public sealed class ControllerActionAttribute : Attribute{    public ControllerActionAttribute();}

Use a strong type to pass ViewData

The previous examples show how to transmit View data from the Controller to the View. In the Controller, there are two ways to transfer View data to the View, one of them is to use a strong type to transmit View data, the following sample code:

[ControllerAction]public void Index(){    BlogRepository repository = new BlogRepository();    List<Post> posts = repository.GetAll();    RenderView("Index", posts);}

A friend mentioned in his reply that how should I pass multiple models or set data to the View? Here we need to define another type:

public class HomeViewData{    public List<Post> Posts    {        get; set;    }    public List<Category> Categories    {        get; set;    }}

Then, the data can be transmitted in the Controller as follows:

[ControllerAction]public void Index(){    BlogRepository repository = new BlogRepository();    List<Post> posts = repository.GetAll();    List<Category> categories = repository.GetAllCategory();    HomeViewData viewData = new HomeViewData();    viewData.Posts = posts;    viewData.Categories = categories;    RenderView("Index", viewData);}

Using a strong type class to pass View data has the following benefits (from Scrottgu ):

1. Avoid using strings to query objects and get the compile-time check for your controller and view code.

2. Avoid explicitly converting the value in the ViewData object dictionary in a strong language such as C #.

3. Obtain the Automatic Code intelliisense of your ViewData object in the identification file of your view webpage and the background code file.

4. Code refactoring tools can be used to automate changes to the entire application and unit test code base.

Use ViewData dictionary to transmit data

In the Controller base class, there is a dictionary definition like this:

public IDictionary<string, object> ViewData { get; }

In this way, we can directly pass the View data through the ViewData field, the following sample code:

[ControllerAction]public void Index(){    BlogRepository repository = new BlogRepository();    List<Post> posts = repository.GetAll();    List<Category> categories = repository.GetAllCategory();    ViewData["posts"] = posts;    ViewData["categories"] = categories;    RenderView("Index");}

In the attempt, you can obtain the View data as follows:

<div>    <%foreach (Post post in (ViewData["posts"] as List<Post>))      { %>    <div class="postitem">        <strong>Title</strong>:<%=Html.Encode(post.Title) %></br>        <strong>Author</strong>:<%=Html.Encode(post.Author) %></br>        <strong>PubDate</strong>:<%=Html.Encode(post.PubDate.ToShortDateString()) %></br>        <strong>Content</strong>:<%=Html.Encode(post.Description) %></br>        <%=Html.ActionLink("Edit", new {action="Edit", Id=post.Id })%>    </div><br />    <% } %></div>
Process unknown actions

The Controller class contains a HandlerUnknownAction method:

protected internal virtual void HandleUnknownAction(string actionName);
This method is used to process unknown actions. By default, the HTTP 404 error is returned. to customize the processing, you can override this method:
[ControllerAction]protected override void HandleUnknownAction(string actionName){    if (ShouldShowSearch(action) == true)    {        RedirectToAction("search", new { query = action });        return;    }    base.HandleUnknownAction(actionName);}

It is used to jump to Search Action when an unknown Action occurs.

Conclusion

In this article, we introduce ASP. net mvc Framework Controller, including how to define Controller and Action, pass View data through strong type and view data dictionary, and customize and process unknown actions. Finally, insert a small advertisement: I established a Web technology Alliance group in the blog community, welcome to join: http://space.cnblogs.com/group/webdev/

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.