Thursday, 11 September 2014

What are the different types of results in MVC?

Note: It’s difficult to remember all the 12 types. But some important ones you can remember for the interview are ActionResult, ViewResult, and JsonResult. Below is a detailed list for your interest:

There 12 kinds of results in MVC, at the top is the ActionResult class which is a base class that can have 11 subtypes as listed below:
  1. ViewResult - Renders a specified view to the response stream
  2. PartialViewResult - Renders a specified partial view to the response stream
  3. EmptyResult - An empty response is returned
  4. RedirectResult - Performs an HTTP redirection to a specified URL
  5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  6. JsonResult - Serializes a given ViewData object to JSON format
  7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  8. ContentResult - Writes content to the response stream without requiring a view
  9. FileContentResult - Returns a file to the client
  10. FileStreamResult - Returns a file to the client, which is provided by a Stream
  11. FilePathResult - Returns a file to the client

What is the difference between ActionResult and ViewResult?

  • ActionResult is an abstract class while ViewResult derives from the  ActionResult class.  ActionResult has several derived classes like  ViewResultJsonResult,  FileStreamResult  and  so on.

  • ActionResult can be used to exploit polymorphism and dynamism. So if you are returning different types of views dynamically, ActionResult is the best thing. For example in the below code snippet, you can see we have a simple action called DynamicView. Depending on the flag (IsHtmlView) it will either return a ViewResult or JsonResult.
public ActionResult DynamicView()
{
   if (IsHtmlView)
     return View(); // returns simple ViewResult
   else
     return Json(); // returns JsonResult view
} 

How to implement AJAX in MVC?

You can implement AJAX in two ways in MVC:

  • AJAX libraries
  • jQuery
Below is a simple sample of how to implement AJAX by using the “AJAX” helper library. In the below code you can see we have a simple form which is created by using the Ajax.BeginForm syntax. This form calls a controller action called getCustomer. So now the submit action click will be an asynchronous AJAX call.
<script language="javascript">
function OnSuccess(data1) 
{
// Do something here
}
</script>
<div>
<%
        var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};        
    %>
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<input id="txtCustomerCode" type="text" /><br />
<input id="txtCustomerName" type="text" /><br />
<input id="Submit2" type="submit" value="submit"/></div>
<%} %> 

In case you want to make AJAX calls on hyperlink clicks, you can use the Ajax.ActionLink function as shown in the below code.
Figure: Implement AJAX in MVC

So if you want to create an AJAX asynchronous hyperlink by name GetDate which calls the GetDate function in the controller, below is the code for that. Once the controller responds, this data is displayed in the HTML DIV tag namedDateDiv.
<span id="DateDiv" />
<%: 
Ajax.ActionLink("Get Date","GetDate",
new AjaxOptions {UpdateTargetId = "DateDiv" })
%> 

Below is the controller code. You can see how the GetDate function has a pause of 10 seconds.
public class Default1Controller : Controller
{
   public string GetDate()
   {
       Thread.Sleep(10000);
       return DateTime.Now.ToString();
   }
}

The second way of making an AJAX call in MVC is by using jQuery. In the below code you can see we are making an AJAX POST call to a URL /MyAjax/getCustomer. This is done by using $.post. All this logic is put into a function calledGetData and you can make a call to the GetData function on a button or a hyperlink click event as you want.
function GetData() 
{
    var url = "/MyAjax/getCustomer";
    $.post(url, function (data) 
    {
        $("#txtCustomerCode").val(data.CustomerCode);
        $("#txtCustomerName").val(data.CustomerName);
    }
    )
} 

What kind of events can be tracked in AJAX?

Figure: Tracked in AJAX

How can you do authentication and authorization in MVC?

You can use Windows or Forms authentication for MVC.

How to implement Windows authentication for MVC?

For Windows authentication you need to modify the web.config file and set the authentication mode to Windows.
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization> 
Then in the controller or on the action, you can use the Authorize attribute which specifies which users have access to these controllers and actions. Below is the code snippet for that. Now only the users specified in the controller and action can access it.
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
public class StartController : Controller
{
    //
    // GET: /Start/
    [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
    public ActionResult Index()
    {
        return View("MyView");
    }
} 

How do you implement Forms authentication in MVC?

Forms authentication is implemented the same way as in ASP.NET. The first step is to set the authentication mode equal to Forms. The loginUrl points to a controller here rather than a page.
<authentication mode="Forms">
<forms loginUrl="~/Home/Login"  timeout="2880"/>
</authentication> 
We also need to create a controller where we will check if the user is proper or not. If the user is proper we will set the cookie value.
public ActionResult Login()
{
    if ((Request.Form["txtUserName"] == "Shiv") && 
          (Request.Form["txtPassword"] == "Shiv@123"))
    {
        FormsAuthentication.SetAuthCookie("Shiv",true);
        return View("About");
    }
    else
    {
        return View("Index");
    }
} 
All the other actions need to be attributed with the Authorize attribute so that any unauthorized user making a call to these controllers will be redirected to the controller (in this case the controller is “Login”) which will do the authentication.
[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
} 

How can we use two ( multiple) models with a single view?

When we bind a model with a view we use the model dropdown as shown in the below figure. In the below figure we can only select one model.


But what if we want to bind “Customer” as well as “Order” class to the view.

For that we need to create a view model which aggregates both the classes as shown in the below code. And then bind that view model with the view.
public class CustOrderVM
{
public Customer cust = new Customer();
public Order Ord = new Order();
}

In the view we can refer both the model using the view model as shown in the below code.

<%= model.cust.Name %>
<%= model.Ord.Number %>

Explain the need of display mode in MVC?

Display mode displays views depending on the device the user has logged in with. So we can create different views for different devices anddisplay mode will handle the rest.

For example we can create a view “Home.aspx” which will render for the desktop computers and Home.Mobile.aspx for mobile devices. Now when an end user sends a request to the MVC application, display mode checks the “user agent” headers and renders the appropriate view to the device accordingly.


Explain MVC model binders?

Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model. Many times HTML UI names are different than the model property names. So in the binder we can write the mapping logic between the UI and the model.