Thursday, 11 September 2014

How did you create a partial view and consume it ?



When you add a view to your project you need to check the “Create partial view” check box.


Figure: Create partial view

Once the partial view is created you can then call the partial view in the main view using the Html.RenderPartialmethod as shown in the below code snippet:

<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body> 

How can we do validations in MVC?


One of the easiest ways of doing validation in MVC is by using data annotations. Data annotations are nothing but attributes which can be applied on model properties. For example, in the below code snippet we have a simpleCustomer class with a property customercode.
This CustomerCode property is tagged with a Required data annotation attribute. In other words if this model is not provided customer code, it will not accept it.

public class Customer
{
    [Required(ErrorMessage="Customer code is required")]
    public string CustomerCode
    {
        set;
        get;
    } 
}  

In order to display the validation error message we need to use the ValidateMessageFor method which belongs to the Html helper class.

<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%> 

Later in the controller we can check if the model is proper or not by using the ModelState.IsValid property and accordingly we can take actions.
public ActionResult PostCustomer(Customer obj)
{
    if (ModelState.IsValid)
    {
        obj.Save();
        return View("Thanks");
    }
    else
    {
        return View("Customer");
    }
}

Below is a simple view of how the error message is displayed on the view.

Figure: Validations in MVC

What are partial views in MVC ?



Partial view is a reusable view (like a user control) which can be embedded inside other view. For example let’s say all your pages of your site have a standard structure with left menu, header, and footer as shown in the image below.


Figure: Partial views in MVC


For every page you would like to reuse the left menu, header, and footer controls. So you can go and create partial views for each of these items and then you call that partial view in the main view.

Wednesday, 10 September 2014

What is the difference between tempdata, viewdata, and viewbag?



Figure: Difference between tempdata, viewdata, and viewbag
  • Temp data - Helps to maintain data when you move from one controller to another controller or from one action to another action. In other words when you redirect, tempdata helps to maintain data between those redirects. It internally uses session variables.
  • View data - Helps to maintain data when you move from controller to view.
  • View Bag - It’s a dynamic wrapper around view data. When you use Viewbag type, casting is not required. It uses the dynamic keyword internally.
Figure: dynamic keyword
  • Session variables - By using session variables we can maintain data from any entity to any entity.
  • Hidden fields and HTML controls - Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.
Below is a summary table which shows the different mechanisms for persistence.
Maintains data betweenViewData/ViewBagTempDataHidden fieldsSession
Controller to ControllerNoYesNoYes
Controller to ViewYesNoNoYes
View to ControllerNoNoYesYes

Explain the concept of MVC Scaffolding?


Scaffolding is a technique in which the MVC template helps to auto-generate CRUD code. CRUD stands for create, read, update and delete.
So to generate code using scaffolding technique we need to select one of the types of templates (leave the empty one).
For instance if you choose “using Entity framework” template the following code is generated.


It creates controller code, view and also table structure as shown in the below figure.



Scaffolding uses Entity framework internally to connect to database.

Monday, 30 June 2014

Top 10 Best Practices when working with ASP.NET MVC applications

In this section we will discuss 10 best practices and tips we should keep in mind when working with ASP.NET MVC applications.

Tip 1: Disable Request Validation

Request Validation is a feature that prevents potentially dangerous content from being submitted. This feature is enabled by default. However, at times you might need your application to post HTML markup tags to the server. You would then need this feature to be disabled. Here is how you can do it:
  1. [ValidateInput(false)]
  2. [AcceptVerbs(HttpVerbs.Post)]
  3. public ActionResult Create([Bind(Exclude="Id")]Employee empObj)
  4. {
  5.  
  6. }

Tip 2: Cache Your Data

You can improve your application's performance to a considerable extent by caching relatively stale data. That way the network bandwidth between the client and the server is also reduced. It is great if you can also cache the rendered action of web pages that are relatively stale, i.e., don’t change much over time.
  1. public class HomeController : Controller
  2. {
  3.     [OutputCache(Duration=3600,
  4. VaryByParam="none")]
  5.     public ActionResult Index()
  6.     {
  7.     
  8.     }
  9. }

Tip 3: Isolate Data Access Logic From the Controller

The Controller in an ASP.NET MVC application should never have the Data Access logic. The Controller in an ASP.NET MVC application is meant to render the appropriate view based on some user interface action. You should make use of Repository Pattern to isolate Data Access Logic from the Controller – you might need dependency injection to inject the appropriate Repository to your controller at runtime.

Tip 4: Using a Master View Model

We frequently use Master Pages in ASP.NET applications – the same Master Page would be extended by the Content Pages throughout the application to give a similarity as far as look and feel and functionality is concerned. How do we do that in an ASP.NET MVC application? Well, we need a MasterViewModel similar to what is shown in the code snippet below:
  1. public class ViewModelBase
  2. {
  3.     public ViewModelBase()
  4.     {
  5.  
  6.     }
  7. //Other methods and properties
  8. }

Tip 5: Use Strongly Typed Models

A strongly typed view is a view that defines its data model as a CLR type instead of a weakly typed dictionary that may contain potentially anything. To create a strongly typed view, check the "Create a strongly-typed view" checkbox while you are creating the view. If you plan to create a strongly typed view manually later, ensure that your view "Inherits" System.Web.Mvc.<Your Namespace>.<YourClass>

Tip 6: Use Data Annotations for Validation

You can make use of the System.ComponentModel.DataAnnotations assembly to validate your server - side code by simply decorating your model with the necessary attributes. Here is an example:
  1. public class Employee
  2. {
  3.     [Required(ErrorMessage="Employee Name Cannot be Blank")]
  4.     public string Name { get; set; }
  5.  
  6.     // ...
  7. }

Tip 7: Take Advantage of Model Binding

Consider the following code snippet:
  1. [AcceptVerbs(HttpVerbs.Post)]
  2. public ActionResult Create()
  3. {
  4.     Employee employee = new Employee();
  5.     employee.Name = Request.Form["Name"];
  6.    
  7.     // ...
  8.    
  9.     return View();
  10. }
You can make use of model binder to save you from having to use the Request and HttpContext properties - just use FormsCollection instead. Here is an example:
  1. public ActionResult Create(FormCollection values)
  2. {
  3.     Employee employee = new Employee();
  4.     employee.Name = values["Name"];     
  5.            
  6.     // ...
  7.            
  8.     return View();
  9. }

Tip 8: Cache Pages that Contain Shared Data or are Public and don't Require Authorization

You should not cache pages that need authorization in ASP.NET MVC. You should not cache pages that contain private data or need authorization. Caching pages in ASP.NET MVC is simple - just specify the OutputCache directive as shown in the code snippet below:
  1. [OutputCache(Duration = 60)]
  2. public ActionResult Index()
  3. {
  4.   return View("Index", somedata);
  5. }

Tip 9: Use Extension Methods

You can make use of Extension Methods to simplifies use of LINQ queries that boost application performance too. This can dramatically reduce the amount of code that you would need to otherwise write when writing your LINQ queries, make your LINQ queries manageable and also improve the application's performance.

Tip 10: Take Advantage of Model Binding

You can take advantage of Microsoft Velocity - a distributed caching engine to boost the application performance of your ASP.NET MVC applications. You can learn more on Velocity from this link:http://blogs.msdn.com/b/velocity/

Suggested Readings