Thursday, 11 September 2014

What is MVC (Model View Controller) ?



MVC is an architectural pattern which separates the representation and user interaction. It’s divided into three broader sections, Model, View, and Controller. Below is how each one of them handles the task.

  • The View is responsible for the look and feel.
  • Model represents the real world object and provides data to the View.
  • The Controller is responsible for taking the end user request and loading the appropriate Model and View.
Figure: MVC (Model view controller)

Can we display all errors in one go?



Yes, we can; use the ValidationSummary method from the Html helper class.

<%= Html.ValidationSummary() %>   

What are the other data annotation attributes for validation in MVC?

If you want to check string length, you can use StringLength.
[StringLength(160)]
public string FirstName { get; set; }

In case you want to use a regular expression, you can use the RegularExpression attribute.
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }

If you want to check whether the numbers are in range, you can use the Range attribute.
[Range(10,25)]
public int Age { get; set; }

Sometimes you would like to compare the value of one field with another field, we can use the Compare attribute.
public string Password { get; set; }
[Compare("Password")]
public string ConfirmPass { get; set; }

In case you want to get a particular error message , you can use the Errors collection.
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;

If you have created the model object yourself you can explicitly call TryUpdateModel in your controller to check if the object is valid or not.
TryUpdateModel(NewCustomer);

In case you want add errors in the controller you can use the AddModelError function.
ModelState.AddModelError("FirstName", "This is my server-side error.");

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.