MVC Basic Questions and answers

What is MVC ?
MVC is a framework which divides application into three components : Models, Views & Controllers.

Model : It consists of all application data, business rules & logic, validation logic and data access logic. All the manipulation of data is done in model.

View : As a name says “View” i.e. what user sees on screen. We can say that it is an Interface which renders model to show application data to the user.

Controller : It is responsible for handling all end user interactions. It Accepts input from user, converts it to commands & loads appropriate Model and View as per input.

What is flow of MVC Application ?

mvc flow
1. Browser Sends request to IIS.
2. IIS searches for route which is defined in MVC application & forwards request to the Controller.
3. As per request controller selects, communicates & loads model.
4. Controller then attaches populated model with the appropriate view.
5. Then Controller sends selected View with model data as response to browser via IIS.

What are New features of MVC 3 & MVC 4 ?
MVC 3 :
1. The Razor view engine.
2. Support for .NET 4 Data Annotations.
3. Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding.
4. Use of NuGet to deliver software and manage dependencies throughout the platform.

MVC 4 :
1. ASP.NET Web API.
2. Enhancements to default project templates.
3. Mobile project template using jQuery Mobile.
4. Display Modes.
5. Task support for Asynchronous Controllers.
6. Bundling and minification.

What are Advantages of using MVC ?
1. More flexibility by Separating UI (View) from Code (controller).
2. As UI is & code are separated, Unit Testing becomes very Easy.
3. We can Reuse Views & Models. We can have single view which can point to multiple models & vice versa.

What is Page Life Cycle of MVC ?
1. App Initialization : Application is started using Application_Start() method is Global.asax.
2. Routing.
3. Instantiate and execute controller.
4. Locate and invoke controller action.
5. Instantiate and render view.

What is Razor Engine View ?
It is special view engine developed with for MVC using razor Parser so that Server side code can be rendered in to Client side code.
Razor is clean, lightweight, and syntax are easy.

What is Unobtrusive JavaScript?
Rather than hooking in via event attributes like onclick and onsubmit, the unobtrusive JavaScript attaches to elements by their ID or class

What are Display Modes in MVC4?
It is convention based approach which allows application to select different views as per browser request. If browser requests from known mobile device then It by default it looks for .Mobile.cshtml & if browser request is from any desktop then it will by default search for .cshtml view.
e.g. If we have View Index.cshtml & Mobile View Index.Mobile.cshtml, then if request comes from known Mobile browser then MVC4 will automatically show mobile view Index.Mobile.cshtml.
We can also create our custom device modes in MVC4. e.g. If you want to add custom display mode for Iphone then you need to following code in Application_start() method of Global.asax.

DisplayModes.Modes.Insert(0, new DefaultDisplayMode("iPhone")

{

ContextCondition = (context =>context.Request.UserAgent.IndexOf

("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)

});

What is ViewData, ViewBag and TempData?
ViewData :
It is dictionary of objects derived from ViewDataDictionary.
It Needs Typecasting to check for null values & avoid any unexpected errors.
ViewData[“data”] = “my data”;
It passes data from controller to view i.e. life lies in current request only.

ViewBag :
It is Dynamic property which takes advantage of new dynamic feature of c# 4.0
It does not require typecasting.
It passes data from controller to view i.e. life lies in current request only.
ViewBag.data = “my data”;

TempData :
TempData is a dictionary derived from the TempDataDictionary class
It needs type casting to check for null values & avoid any unexpected errors.
TempData[“data”] = “my Data”;
It maintains data when moving from one controller to another or one action to another.It can maintain data when moving from one page to another.

What is Routing in MVC ?
Routing means mapping incoming browser request to particular MVC controller action.
Routing Code :

            
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Where are the routing rules defined in an asp.net MVC application?
In MVC 3 it is defined in Application_Start() method of global.asax file.
In MVC 4 routing rules are defined in RouteConfig.cs file which is called from Application_Start() method of global.asax file.

How route table is created in MVC ?
When application starts it calls application_start() method of global.asax file. This method calls Registerroutes() method which creates route table for MVC application.

What are Layouts in MVC ?
Layouts are used to maintain consistence look and feel across multiple views within an application.
It is similar to master pages of asp.net web forms but layouts provides more flexibility & simplicity.

@{
       Layout = "~/Views/Shared/AppLayout.cshtml";
}

We can create Nested Layout also for views just like we create nested master pages in asp.net application.

What is ViewStart?
Code of _ViewStart.cshtml is executed just before code of view of same directory is executed.
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering.
Common view code of _ViewStart.cshtml can be overridden in views.
e.g. Lets say we have _ViewStart.cshtml which has follwing code

@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

As per code we can see that _Layout.cshtml will be Layout page for all the views.
But what if I want to change Layout page for some view ?
Then we can just override Layout in View like this :

@{
    Layout = "~/Views/Shared/OtherLayout.cshtml";
}

What are Html Helpers ?
HTML Helpers are methods which helps to render HTML control in the views.
e.g. e.g.

@Html.ActionLink("About this Website", "About") 

which will create

<a href="/Home/About">About this Website</a> HTML code.

There are may HTML Helpers, some of them are :
BeginForm()
EndForm()
TextArea()
TextBox()
CheckBox()
RadioButton()
ListBox()
DropDownList()
Hidden()
Password()

There are also URL helpers and AJAX helpers which can be used in Views in MVC.

Html.BegainForm

@{Html.BegainForm(“actionName”,”controllerName”,”form method I.e POST or GET”);}

It creates

Html tag
e.g. If we write this

@{Html.BegainForm(“about”,”home”,FormMethod.Post);}
@{Html.Endform();}

Here Html.BegainForm will create
and Html.Endform will create closing tag

.
So full HTML tag generated will be

<form method="post" action="/home/about"></form>

Usually it is used with using tag like this

@using(Html.BegainForm(“about”,”home”,FormMethod.Post))
{
// he we can write out own html.
}

Html.ActionLink

@Html.ActionLink(“Display Text”,“Action”,”Controller”,”Optional Parameters”)

It will create html tag
e.g.

@Html.ActionLink(“My Display Text”,”About”,”Home”,new{myValue = 1})

then it will create bellow tag.

<a href="/Home/About?myValue=1"></a>

and “My Diplay Text ” will be shown to user on the page.

Html.CheckBox()

@Html.CheckBox(“NameAttributeValueOfCheckbox”,optional parameters);

it will create

<input type=”checkbox” name=”NameAttributeValueOfCheckbox” /> html tag

e.g.

@Html.CheckBox("NameAttribute", new { id = "drsc", @class = "comp", value = "100"})

it will create bellow html tag

<input id="drsc" class="comp" type="checkbox" value="100" name="NameAttribute"></input>

Html.CheckBoxFor()
e.g.

@Html.CheckBoxFor(x => x.Name, new{id=”myId1”});

it will create

<input id="myId1" name="Name" type="checkbox" value="true" /> HTML tag.

Value for name attribute will be as per model property assigned to the CheckBox.

What are partial views in MVC?
Partial view is a reusable view which can be embedded in other view.
E.g. If you have header,content & footer as structure of your page. If you want to repeat header & footer for other pages then we can create partial views for header & footer & embed them in other views.

Partial view can be embedded in two ways
1. @{Html.RenderPartial(“MyView”);}
2. @Html.Partial(“MyView”);

What area ajax helpers in MVC ?

Ajax.BeginForm
In Ajax.BeginForm, you can specify the following arguments
1. Action Name.
2. Controller Name.
3. ajaxOptions : An object that provides options for the asynchronous request.
This has many overloads. See them at : http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxextensions.beginform.aspx

using (Ajax.BeginForm("ActionName", "ControllerName", new AjaxOptions {HttpMethod = "POST", UpdateTargetId = "myDivId",OnSuccess="JavaScriptFunctionWhichWillBeCalledAfterSuccess" })) 
{
// logic + submit button
}

Just Like OnSuccess it have more three options
1. OnBegin
2. OnComplete
3. OnFailure

Also it has option UpdateTargetId where you can pass id of div which will be updated after response comes.

Ajax.ActionLink

@Ajax.ActionLink(“Get Date”,”GetDate,”Home”})

It is similar to Html.ActionLink.

How to implement Validations in mvc ?
View My Post
Implementing Validations in MVC For Answer.

How to implement form authentication in mvc ?
View My Post Implementing form authentication in MVC For Answer.

How are results in mvc ?
View My Post Implementing result types in MVC For Answer.

What are filters in mvc ?
View My Post Implementing filters in MVC For Answer.

What is Web API ?
It is technology which transfers data over HTTP using REST (Representational state transfer).

What Is REST ?
REST is an architecture style for designing networked applications which is independent of any transfer protocol. Most commonly rest is used with HTTP.

admin