My ASP.NET MVC3 Notes(1)

01 - Controllers in ASP.NET MVC 3

Application_Start() method  in Global.asax.cs is the startup entry of the application

image

Using RouteData object to get information of routing data

image

In the route collection, the first route that matches the URL will Win, so we should put our particular route before the very greedy Default route

image

If there’s a parameter in the action method, the MVC framework will do everything it can to populate that parameter from routing data, query string and post form value

image

Actions typically return an ActionResult

image

Examples of different ActionResult:

   return Json(new { cuisinName = name}, JsonRequestBehavior.AllowGet;

image
image
image
image

Action selectors: [HttpPost] , [HttpGet]

image

Action Filters:

image

[Authorize] filter will redirect to the log on page if the user  access this particular method before logging in:

image

[OutputCache] filter

Before MVC3, [OutputCache] can only cache everything inside the view or cache nothing, but now in MVC3 it can cache individual Child ViewResult, such as PatialView.

image

[HandleError] filter

In previouse version, HandlError filter can be only applied to Action mothods

image

While in MVC3, we can put it to Global.asax.cs as an global filter:

image

and then we need to turn on the customErrors mode in web.config file

image

and of course we need to put some friendly error message to the \Shared\Error.cshtml  file

image

We can also provide our own filter attribut, which inherits the ActionFilterAttute base class

image

ViewBag & ViewData

In previous versions of MVC, controler uses ViewData dictionary to provide data to View, while in MVC3, we can use ViewBag, which uses Property instead of key name

image
image

Request Validation

Generally ASP.NET Framework will reject embedded html values posted from a form:

image
image

In MVC2, we can apply [ValidateInput(false)] to turn off the validation for this action:

image

But this will afftect all the fields in the view modle, in this example if we want to only disable the validation for Description field and reject embedded HTML value for Name field, in MVC3, we only need to apply [AllowHtml] attribute to Description property in Instructor model class:

image
posted @ 2011-06-11 05:55  Jian, Li  Views(690)  Comments(0)    收藏  举报