In this blog, I will document some of the useful notes while creating ASP.NET MVC applications. This blog can be used as a quick refresher for ASP.NET MVC concepts.
Partial Views
- The lang attribute in html element allows to specify what language the HTML text is in. This helps the text to speech converters, selecting right fonts, right dictionary etc
- meta tag character encoding is required to avoid some strange cross site scripting attacks. If not specified, an attacker can make the browser think that the encoding is UTF-7. Then he can inject UTF-7 encoded scripts into the page
- the meta element with name "viewport" is used to give sizing instructions to mobile devices
Models
- represent actual data to be displayed
- have no clue about view or controllers
- use @model directive to specify the type of model used on the view
- use @Model to actually use the model
Controller
- are targets for incoming HTTP requests
- are responsible for creating/fetching the models
- after model is generated they select a view to display the model.
- have no idea about display features. That is in the view.
- knows about both models and views
View
- have no idea about DAL
- have no idea about controller but know the model to display
ViewBag - dynamically typed object
Routes
- Routing engine is core to ASP.NET and not just for MVC. The routing engine can be used to call webforms, WCF services etc
- we can inspect the route values by using the RouteData.Values dictionary
- the order in which we specify the routes is important
- routing engine will look into everything in the request to populate action parameters. It will look in URL, RouteData, query strings and posted form values
Action Results
- actions return ActionResult
- ActionResult is a base class with many derived types
- ContentResult - returns a string
- EmptyResult - no response
- FileContentResult, FilePathResult, FileStreamResult - returns file contents. Called via File()
- HttpUnauthorizedResult - HTTP 403
- JavaScriptResult - returns a js to execute.
- JsonResult - returns data in json format.
- RedirectResult - redirects client to a new url
- RedirectToRouteResult - redirects to another action or another controller's action. Called via RedirectToRoute or RedirectToAction
- ViewResult, PartialViewResult - response will be sent by view engine. called via View() or PartialView()
- allows us to apply pre and post processing logic and its results
- many ready to use filters
- OutputCache - cache the output of a controller
- ValidateInput - turn off request validation and allow dangerous input
- Authorize - Restrict an action to authorized users or roles
- ValidateAntiForgeryToken - to prevent CSRF attacks
- HandleError - in case of unhandled exception specifies a view to render
- besides this we can also create our own custom filters by inheriting from ActionFilterAttribute
- if we want to apply the filter to all controllers globally, we can do so by adding them to global filters collection in Global.asax
- are like templates
- template + data = output
- Razor views automatically HTML encode the output to avoid XSS attacks
- To escape the @ sign in razor views use another @ for ex to show twitter handle @twitter, write as @@twitter
- @: tells razor that this is literal text. This can be used to output literal text inside of code blocks.
- In the _ViewStart.cshtml we specify the Layout property of the view. Anything specified in this file will mean that this code gets executed first before the view.
- @RenderBody() is a required method
- sections can be rendered using @RenderSection method. This allows say for example an index page to publish some html in different sections in the layout page.
- @Html
- Html is a property of ViewPage base class to emit HTML code i.e links, forms and inputs
- Html.EditorFor() inspects the type of object passed and creates an html element. For ex for bool it will create checkbox and for string it will create a textbox
- Html.BeginForm() will emit a form tag. We can pass parameters to it to specify the method (get or post) and action url. By Default it will use the same action url with post method. The HTML output would be similar to <form action="/somecontroller/someaction/2" method="post">...</form>
- Html.HidderFor() will output an input tag with type = hidden
- the goal of html helpers is to keep views simple by putting the c# logic in helpers
- if you find lot of logic being written in views, try creating html helpers
What does HTML Encoding do?
- HTML encoding is used to avoid Cross Site Scripting attacks (XSS)
- If in an action we write something like return Content("<script>alert('xss attack')</script>"); the javascript will get executed, however, if we write return Content(Server.HtmlEncode("<script>alert('xss attack')</script>")); the content will be output as text instead of javascript.
- the Server.HtmlEncode function internally will convert < to < etc to instruct the browser that we need to display them as text rather than see it as an opening script tag and start executing the script
- if we want to display the HTML as it is without encoding it, we can use @Html.Raw() in razor views
- if we need to reuse the views we can use partial views.
- partial views can be called in 2 ways
- by calling Html.Partial()
- by calling Html.Action() where the action returns a PartialViewResult. Since this action returns a partial view, it might not be useful for this action to be called from browser. So we can use the attribute ChildActionOnly on top of the action. This will ensure that the action will not get called as a single request.