Wednesday, August 17, 2011

Tips & Tricks of ASP.NET MVC3



RAZOR
Problem 1:


Error: 'string' does not contain a definition for 'jpg'

Fix:



Problem 2:

Twitter : @MyTwitterHandle
Error: 'MyTwitterHandle' does not exist in the current context

Fix:

Twitter : @@MyTwitterHandle

Problem 3:

@{
var persons= "Deba, Ramesh, David";
if (persons.Contains("Deba"))
{
Your name is in the list
}
else
{
Your name isn't in the list
}

Error : ; Expected

Fix:

@{
var persons= "Deba, Ramesh, David";
if (persons.Contains("Deba"))
{
Your name is in the list
}
else
{
Your name isn't in the list
}
}


Problem 4:

@{
var message = "Hello Deba";
message
}
Output: Hello Deba

Fix:

@{
var message = "Hello Deba";
@Html.Raw(message)
}
Output : Hello Deba

Patterns
1. Create extension method of URL Helper
2. Use Bootstraper in Global.asax if you have lot of things in Application_Start
3. Decorate your actions with proper AcceptVerbs and CacheControl.
4. Use Depedency Injection
5. Use Typed Views
6. Async Controllers
7. Avoid having huge numbers registrations in Global.asax. Ulternate is- Use Attribute based Route Mapper. http://maproutes.codeplex.com/
8. Use Post-Redirect-Get pattern

[HttpGet]
public ActionResult Employee()
{
return View("Employee");
}
[HttpPost]
public ActionResult Employee(Employee e)
{
if (!Validate(e))
{
return View("Employee", e);
}
RedirectToAction("AddEmployee");
}

9. No Magic Strings

Using expression based Form generation - Html.TextBoxFor(order=>order.Customer.Name)
Using expression based URL generation - Url.Action(c=>c.Index())
Using expression based RedirectToAction - RedirectToAction(c=>c.Index())

10. Keep your controller free from HttpContent. If you require to use it, then use custom action filter or interface or wrapper.
10. Reusing view logic by using @helper.
Step1 - Create a view in App_Code folder and write all your helper methods.
Ex:

@helper FormatCurrency(Decimal price)
{
@price.ToString("c")
}

Step 2 - Calling the helper method

@FormatCurrency(product.price)


Issue with @helper - Built-in Html helper methods are not available inside the views in App_Code. Fix - http://blogs.msdn.com/b/davidebb/archive/2010/10/27/turn-your-razor-helpers-into-reusable-libraries.aspx


Related Topics -
MVC 3 Tools Update


ASP.NET MVC WebGrid

No comments:

Post a Comment