Sunday, June 30, 2013

MVC Basic Interview question Answer

Question 1: What is MVC in asp.net? 

AnswerMVC is a framework for building web applications using a MVC (Model View Controller) design:

  •  The Model represents the application core (for instance a list of database records).   
  •  The View displays the data (the database records).
  •  The Controller handles the input (to the database records).
Question 2:  What's the difference between ActionResult and ViewResult for action method?

Answer : In MVC framework, it uses ActionResult class to reference the object your action method returns.                        
             And invokes ExecuteResult method on it.
             ViewResult is an implementation for this abstract class. It will try to find a view page (usually aspx        page) in some predefined paths(/views/controllername/, /views/shared/, etc) by the given view name.
       
Question 3:What are routing in MVC?
Answer : Routing helps you to define a URL structure and map the URL with the controller. For instance let’s say we want that when any user types “http://localhost/View/ViewCustomer/”,  it goes       to the  “Customer” Controller  and invokes “DisplayCustomer” action.  This is defined by adding an entry in   to the “routes” collection using the “maproute” function. Below is the under lined code which shows how the      URL structure and mapping with controller and action is defined.   
routes.MapRoute(
               "View", // Route name
               "View/ViewCustomer/{id}", // URL with parameters
               new { controller = "Customer", action = "DisplayCustomer",  
id = UrlParameter.Optional }); // Parameter defaults   

Question 4 :Where is the route mapping code written?

Answer :The route mapping code is written in the “global.asax” file.

Question 5 :Can we map multiple URL’s to the same action?
Answer :Yes , you can , you just need to make two entries with different key names and specify the same controller and action.
Question 6 :How can we navigate from one view to other view using hyperlink?

Answer :By using “ActionLink” method as shown in the below code. The below code will create a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.
<%= Html.ActionLink("Home","Gotohome") %>
  
Question 7 :How can we restrict MVC actions to be invoked only by GET or POST?

Answer :We can decorate the MVC action by “HttpGet” or “HttpPost” attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the “DisplayCustomer” action can only be invoked by “HttpGet”. If we try to make Http post on “DisplayCustomer” it will throw an error.

[HttpGet]
        public ViewResult DisplayCustomer(int id)
        {
            Customer objCustomer = Customers[id];
            return View("DisplayCustomer",objCustomer);
        } 
Question 8 :How can we maintain session in MVC?

Answer :Sessions can be maintained in MVC by 3 ways tempdata ,viewdata and viewbag.

Question 9: What is the difference between tempdata ,viewdata and viewbag?

Answer :Temp data: -Helps to maintain data when you move from one controller to other controller or from one action to other 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.

Question 10: What are the different types of results in MVC? 

Answer :There 12 kinds of results in MVC, at the top is “ActionResult”class which is a base class that canhave11subtypes’sas listed below: -
ViewResult - Renders a specified view to the response stream
PartialViewResult - Renders a specified partial view to the response stream
EmptyResult - An empty response is returned
RedirectResult - Performs an HTTP redirection to a specified URL
RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
JsonResult - Serializes a given ViewData object to JSON format
JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
ContentResult - Writes content to the response stream without requiring a view
FileContentResult - Returns a file to the client
FileStreamResult - Returns a file to the client, which is provided by a Stream
FilePathResult - Returns a file to the client

Question 11-Can we create our custom view engine using MVC?

Answer :Yes, we can create our own custom view engine in MVC. To create our own custom view engine we need to follow 3 steps:-

Let’ say we want to create a custom view engine where in the user can type a command like “<DateTime>” and it should display the current date and time.

Question 12:How to send result back in JSON format in MVC?

Answer :In MVC we have “JsonResult” class by which we can return back data in JSON format. Below is a simple sample code which returns back “Customer” object in JSON format using “JsonResult”.
public JsonResult getCustomer()
{
Customer obj = new Customer();
obj.CustomerCode = "1001";
obj.CustomerName = "Shiv";
 return Json(obj,JsonRequestBehavior.AllowGet);
}

Question 13:What is “WebAPI”?

Answer :HTTP is the most used protocol.For past many years browser was the most preferred client by which we can consume data exposed over HTTP. But as years passed by client variety started spreading out. We had demand to consume data on HTTP from clients like mobile,javascripts,windows  application etc.

For satisfying the broad range of client “REST” was the proposed approach. You can read more about “REST” from WCF chapter.

“WebAPI” is the technology by which you can expose data over HTTP following REST principles.
Question 14:With WCF also you can implement REST,So why "WebAPI"?
Answer :WCF was brought in to implement SOA, never the intention was to implement REST."WebAPI'" is built from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for creating “REST” service “WebAPI” is more preferred.

Question 15:How to implement Ajax in MVC?
Answer :You can implement Ajax in two ways in MVC: -

Ajax libraries
Jquery
Below is a simple sample of how to implement Ajax by using “Ajax” helper library. In the below code you can see we have a simple form which is created by using “Ajax.BeginForm” syntax. This form calls a controller action called as “getCustomer”. So now the submit action click will be an asynchronous ajax call.
Question 16:How do you implement forms authentication in MVC?
Answer :Forms authentication is implemented the same way as we do in ASP.NET. So the first step is to set authentication mode equal to forms. The “loginUrl” points to a controller here rather than page.


<authentication mode="Forms">
<forms loginUrl="~/Home/Login"  timeout="2880"/>
</authentication> 
We also need to create a controller where we will check 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 “Authorize” attribute so that any unauthorized user if he makes a call to these controllers it will redirect to the controller ( in this case the controller is “Login”) which will do authentication.

[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();

Question 16:How can we do validations in MVC? 

Answer :One of the easy ways of doing validation in MVC is by using data annotations. Data annotations are nothing but attributes which you can be applied on the model properties. For example in the below code snippet we have a simple “customer” 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 the same.

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 “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 “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");
}

Question 17:Can we display all errors in one go?

Answer :Yes we can, use “ValidationSummary” method from HTML helper class.

Question 18: How can we enable data annotation validation on client side?

Answer :It’s a two-step process first reference the necessary jquery files.


<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script> 
Second step is to call “EnableClientValidation” method.


<% Html.EnableClientValidation(); %>

Question 19:What is razor in MVC? 

Answer :It’s a light weight view engine. Till MVC we had only one view type i.e.ASPX, Razor was introduced in MVC 3.

Question 20:Why razor when we already had ASPX?

Answer :Razor is clean, lightweight and syntaxes are easy as compared to ASPX. For example in ASPX to display simple time we need to write.


<%=DateTime.Now%> 
In Razor it’s just one line of code.


@DateTime.Now
Question 21 :So which is a better fit Razor or ASPX?

Answer :As per Microsoft razor is more preferred because it’s light weight and has simple syntaxes.

Question 22: How can you do authentication and authorization in MVC?

Answer :You can use windows or forms authentication for MVC.