Saturday, January 30, 2010

ASP.NET MVC Best practises

1. Should I pass the Controller, Acton or route name as string ?
Ans. Avoid passing the controller, action or route name as string, create extension methods of UrlHelper which encapsulates it.
2. What is the best practice to refer my Asset (Image, javascript, stylesheet) ?
Ans. Create Extension Method of UrlHelper to map your JavaScript, Stylesheet and Image Folder.
3. How should I instantiate instance of my controller classes ?
Ans. Do not make any hard dependency on the DI Container, use Common Service Locator.
4. When to use HttpVerbs.Get and HttpVerbs.Post ?
Ans. Make sure the action methods that modifies the data only accepts HttpVerbs.Post.
5. When should I use OutputCache Attribute ?
Ans. Decorate your most frequent Action Methods with OutputCache Attribute.
6. Is it right to use HttpContext in my Controller class ? How to unit test my Controller that uses HttpContext ?
Ans. Keep your controller free from HttpContext and its tail. If you need to access anything from HttpContext like User, QueryString, Cookie etc use custom action filter or create some interface and wrapper and pass it in the constructor.
7. How to convert proper data types from route value/Query string ?
Ans. Use Action Filter to Convert to compatible Action Methods parameters
8. Can I use same ActionFilter at Controller level instead of using it to all its action methods ?
Ans. yes.
9. Use UpdateModel Carefully
10. Should I write Domain logic in Controller ?
Ans. Controller will not contain any Domain logic.
11. Avoid ViewData, use ViewData.Model
12. I am copying ModelState to TempData manaully when a exception occurs or validation fails. It is right ?
Ans. Use an ActionFilter to do this instead.
13. what is best way to populate common data like Username, IsAuthenticated etc. to View Model ?
Ans. Create Layer Super Type for your ViewModel and Use Action Filter to populate common parts.
14. Split your View into multiple ViewUserControl for better readability.
15. Use HtmlHelper extension for reusable UI elements ?
16. Do I need to Encode for html element attribute ?
Ans. Whatever you receive from the User always use Html.Encode(“User Input”) for textNode and Html.AttributeEncode(“User Input”) for html element attribute.
17. Do not put your JavaScript codes in your View.
18. Use jQuery and jQuery UI

No comments:

Post a Comment