MVC Interview Questions and Answers PDF
MVC Interview Questions and Answers PDF
by www.questpond.com For more than 600+ .NET interview & fundamental questions, email us on questpond@questpond.com or Call us on +91-22-66752917
What is MVC(Model view controller)? Can you explain the complete flow of MVC? Is MVC suitable for both windows and web application? What are the benefits of using MVC? Is MVC different from a 3 layered architecture? What is the latest version of MVC? What is the difference between each version of MVC? What are routing in MVC? Where is the route mapping code written? Can we map multiple URLs to the same action? How can we navigate from one view to other view using hyperlink? How can we restrict MVC actions to be invoked only by GET or POST? How can we maintain session in MVC? What is the difference between tempdata,viewdata and viewbag? What are partial views in MVC? How did you create partial view and consume the same? How can we do validations in MVC? Can we display all errors in one go? How can we enable data annotation validation on client side? What is razor in MVC? Why razor when we already had ASPX? So which is a better fit Razor or ASPX? How can you do authentication and authorization in MVC? How to implement windows authentication for MVC? How do you implement forms authentication in MVC? How to implement Ajax in MVC? What kind of events can be tracked in AJAX? What is the difference between ActionResult and ViewResult? What are the different types of results in MVC? What are ActionFiltersin MVC? Can we create our custom view engine using MVC? How to send result back in JSON format in MVC? What is WebAPI? But WCF SOAP also does the same thing, so how does WebAPI differ? With WCF also you can implement REST, So why "WebAPI"? How can we detect that a MVC controller is called by POST or GET?
The View is responsible for look and feel. Model represents the real world object and provides data to the View. The Controller is responsible to take the end user request and load the appropriate Model and View.
All end user requests are first sent to the controller. The controller depending on the request decides which model to load. The controller loads the model and attaches the model with the appropriate view. The final view is then attached with the model data and sent as a response to the end user on the browser.
HTML 5 enabled templatesSupport for Multiple View EnginesJavaScript Many new features to support mobile and Ajax apps Model Validation Improvements Enhanced support for asynchronous methods
How can we navigate from one view to other view using hyperlink?
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")%>
Figure:- difference between tempdata , viewdata and viewbag 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: - Its 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 different mechanism of persistence. Maintains data between Controller to Controller Controller to View View to Controller ViewData/ViewBag No Yes No TempData Yes No No Hidden fields No No Yes Session Yes Yes Yes
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.
How did you create partial view and consume the same?
When you add a view to your project you need to check the Create partial view check box.
Figure:-createpartialview Once the partial view is created you can then call the partial view in the main view using Html.RenderPartial method as shown in the below code snippet. . <body> <div> <%Html.RenderPartial("MyView");%> </div> </body>
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)%> <inputtype="submit"value="Submitcustomerdata"/> <%}%> 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.
.
publicActionResultPostCustomer(Customerobj) { if(ModelState.IsValid) { obj.Save(); returnView("Thanks"); } else { returnView("Customer"); } } Below is a simple view of how the error message is displayed on the view.
<%=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)] publicstringFirstName{get;set;} In case you want to use regular expression, you can use RegularExpression attribute.
[RegularExpression(@"[AZaz09._%+]+@[AZaz09.]+\.[AZaz]{2,4}")]publicstringEmail{ get;set;} If you want to check whether the numbers are in range, you can use the Range attribute.
.
[Range(10,25)]publicintAge{get;set;} Some time you would like to compare value of one field with other field, we can use the Compare attribute.
.
publicstringPassword{get;set;}[Compare("Password")]publicstringConfirmPass{get;set; } In case you want to get a particular error message , you can use the Errors collection.
varErrMessage=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 AddModelError function. ModelState.AddModelError("FirstName","Thisismyserversideerror.");
else { returnView("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] PublicActionResultDefault() { returnView(); } [Authorize] publicActionResultAbout() { returnView(); }
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. <scriptlanguage="javascript"> functionOnSuccess(data1) { //Dosomethinghere } </script> <div> <% varAjaxOpt=newAjaxOptions{OnSuccess="OnSuccess"}; %> <%using(Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)){%> <inputid="txtCustomerCode"type="text"/><br/> <inputid="txtCustomerName"type="text"/><br/> <inputid="Submit2"type="submit"value="submit"/></div> <%}%> In case you want to make ajax calls on hyperlink clicks you can use Ajax.ActionLink function as shown in the below code.
So if you want to create Ajax asynchronous hyperlink by name GetDate which calls the GetDate function on the controller , below is the code for the same. Once the controller responds this data is displayed in the HTML DIV tag by name DateDiv.
<spanid="DateDiv"/> <%: Ajax.ActionLink("GetDate","GetDate", newAjaxOptions{UpdateTargetId="DateDiv"}) %> Below is the controller code. You can see how GetDate function has a pause of 10 seconds. publicclassDefault1Controller:Controller { publicstringGetDate() { Thread.Sleep(10000); returnDateTime.Now.ToString(); } } The second way of making 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 in to a function called as GetData and you can make a call to the GetData function on a button or a hyper link click event as you want. functionGetData() { varurl="/MyAjax/getCustomer"; $.post(url,function(data) { $("#txtCustomerCode").val(data.CustomerCode); $("#txtCustomerName").val(data.CustomerName); } ) }
Figure:- ActionFiltersin MVC Action filters are useful in the following scenarios:1. 2. 3. 4. Implement post-processinglogicbeforethe action happens. Cancel a current execution. Inspect the returned value. Provide extra data to the action.
Inline action filter. Creating an ActionFilter attribute. To create a inline action attribute we need to implement IActionFilter interface.The IActionFilter interface has two methods OnActionExecuted and OnActionExecuting. We can implement pre-processing logic or cancellation logic in these methods. publicclassDefault1Controller:Controller,IActionFilter { publicActionResultIndex(Customerobj) { returnView(obj); } voidIActionFilter.OnActionExecuted(ActionExecutedContextfilterContext) { Trace.WriteLine("ActionExecuted"); } voidIActionFilter.OnActionExecuting(ActionExecutingContextfilterContext) { Trace.WriteLine("Actionisexecuting"); } } The problem with inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter to an action filter attribute. To create an action filter attribute we need to inherit from ActionFilterAttribute and implement IActionFilter interface as shown in the below code. publicclassMyActionAttribute:ActionFilterAttribute,IActionFilter { voidIActionFilter.OnActionExecuted(ActionExecutedContextfilterContext) { Trace.WriteLine("ActionExecuted"); } voidIActionFilter.OnActionExecuting(ActionExecutingContextfilterContext) { Trace.WriteLine("Actionexecuting"); } } Later we can decorate the controllers on which we want the action attribute to execute. You can see in the below code I have decorated the Default1Controller with MyActionAttribute class which was created in the previous code. [MyActionAttribute] publicclassDefault1Controller:Controller { publicActionResultIndex(Customerobj) { returnView(obj); } }
Step 1:- We need to create a class which implements IView interface. In this class we should write the logic of how the view will be rendered in the render function. Below is a simple code snippet for the same. publicclassMyCustomView:IView { privatestring_FolderPath;//Definewhereourviewsarestored publicstringFolderPath { get{return_FolderPath;} set{_FolderPath=value;} } publicvoidRender(ViewContextviewContext,System.IO.TextWriterwriter) { //Parsinglogic<dateTime> //readtheviewfile stringstrFileData=File.ReadAllText(_FolderPath); //weneedtoandreplace<datetime>datetime.nowvalue stringstrFinal=strFileData.Replace("<DateTime>",DateTime.Now.ToString()); //thisreplaceddatahastosentfordisplay writer.Write(strFinal); } } Step 2 :-We need to create a class which inherits from VirtualPathProviderViewEngine and in this class we need to provide the folder path and the extension of the view name. For instance for razor the extension is cshtml , for aspx the view extension is .aspx , so in the same way for our custom view we need to provide an extension. Below is how the code looks like. You can see the ViewLocationFormats is set to the Views folder and the extension is .myview. publicclassMyViewEngineProvider:VirtualPathProviderViewEngine { //WewillcreatetheobjectofMycustomeview publicMyViewEngineProvider()//constructor { //DefinethelocationoftheViewfile this.ViewLocationFormats=newstring[]{"~/Views/{1}/{0}.myview", "~/Views/Shared/{0}.myview"};//locationandextensionofourviews } protectedoverrideIViewCreateView(ControllerContextcontrollerContext,string viewPath,stringmasterPath) { varphysicalpath=controllerContext.HttpContext.Server.MapPath(viewPath); MyCustomViewobj=newMyCustomView();//Customviewengineclass obj.FolderPath=physicalpath;//setthepathwheretheviewswillbestored returnobj;//returnedthisviewparesinglogicsothatitcanberegisteredin theviewenginecollection } protectedoverrideIViewCreatePartialView(ControllerContextcontrollerContext,string partialPath) { varphysicalpath=controllerContext.HttpContext.Server.MapPath(partialPath); MyCustomViewobj=newMyCustomView();//Customviewengineclass obj.FolderPath=physicalpath;//setthepathwheretheviewswillbestored returnobj;//returnedthisviewparesinglogicsothatitcanberegisteredin theviewenginecollection } } Step 3:- We need to register the view in the custom view collection. The best place to register the custom view engine in the ViewEngines collection is the global.asax file. Below is the code snippet for the same. protectedvoidApplication_Start() { //Step3:registerthisobjectintheviewenginecollection
ViewEngines.Engines.Add(newMyViewEngineProvider()); <spanclass="Appletabspan"style="whitespace:pre;"> </span>.. } Below is a simple output of the custom view written using the commands defined at the top.
Figure:-customviewengineusingMVC If you invoke this view you should see the following output.
What is WebAPI?
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.
But WCF SOAP also does the same thing, so how does WebAPI differ?
SOAP Size Heavy weight because of complicated WSDL structure. WEB API Light weight, only the necessary information is transferred. Only for HTTP protocol
Protocol Independent of protocols. To parse SOAP message, the client needs to understand WSDL format. Writing custom code for parsing WSDL is Output of WebAPI are simple string Formats a heavy duty task. If your client is smart enough to message,JSON,Simple XML format etc. So writing create proxy objects like how we have in .NET (add parsing logic for the same in very easy. reference) then SOAP is easier to consume and call. WEB API follows REST principles. (Please refer about Principles SOAP follows WS-* specification. REST in WCF chapter).
Figure:- implement WebAPI in MVC Step 2:- Once you have created the project you will notice that the controller now inherits from "ApiController" and you can now implement "post","get","put" and "delete" methods of HTTP protocol. publicclassValuesController:ApiController { //GETapi/values publicIEnumerable<string>Get() { returnnewstring[]{"value1","value2"}; } //GETapi/values/5 publicstringGet(intid) {
return"value"; } //POSTapi/values publicvoidPost([FromBody]stringvalue) { } //PUTapi/values/5 publicvoidPut(intid,[FromBody]stringvalue) { } //DELETEapi/values/5 publicvoidDelete(intid) { } } Step 3:-If you make a HTTP GET call you should get the below results.
Figure:- HTTP