MVC Interview Questions
MVC Interview Questions
Any web application has two main execution steps first understanding
the request and depending on the type of the request sending out
appropriate response. MVC application life cycle is not different it has
two main phases first creating the request object and second sending
our response to the browser.
Creating the request object: -The request object creation has four
major steps. Below is the detail explanation of the same.
Step 1 Fill route: - MVC requests are mapped to route tables which in
turn specify which controller and action to be invoked. So if the request
is the first request the first thing is to fill the route table with routes
collection. This filling of route table happens in the global.asax file.
Separation of concerns is achieved as we are moving the codebehind to a separate class file. By moving the binding code to a
separate class file we can reuse the code to a great extent.
MVC 4
ASP.NET
Web API
Areas
Asynchronous
Controllers
Html.ValidationSummary
Helper Method
DefaultValueAttribute in
Action-Method
Parameters binding
Binary data with Model
Binders
DataAnnotations
Attributes
Model-Validator
Providers
New
RequireHttpsAttribute
Action Filter
Templated Helpers
Display
Model-Level
Errors
project
templates
HTML
5
enabled
templates
Support for
Multiple
View
Engines,
JavaScript,
and AJAX
Model
Validation
Improvemen
ts
Refreshed
and
modernize
d default
project
templates.
New
mobile
project
template.
Many new
features to
support
mobile
apps
Enhanced
support for
asynchrono
us methods
@Html.CheckBox("Married")
routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults
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 - Its a dynamic wrapper around view data. When you
use Viewbag type, casting is not required. It uses the dynamic
keyword internally.
No
Yes
No
Yes
Yes
18) 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.
if (ModelState.IsValid)
{
obj.Save();
return View("Thanks");
}
else
{
return View("Customer");
}
}
<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>
}
[Authorize]
publicActionResult About()
{
return View();
}
AJAX libraries
jQuery
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 called GetData 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);
}
)
}
}
}
The problem with the 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 the IActionFilter interface as
shown in the below code.
public class MyActionAttribute : ActionFilterAttribute , IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext
filterContext)
{
Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext
filterContext)
{
Trace.WriteLine("Action executing");
}
}
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 the MyActionAttribute class which was
created in the previous code.
[MyActionAttribute]
public class Default1Controller : Controller
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
}
var
physicalpath
=
controllerContext.HttpContext.Server.MapPath(viewPath);
MyCustomView obj = new MyCustomView(); // Custom view
engine class
obj.FolderPath = physicalpath; // set the path where the views will
be stored
return obj; // returned this view paresing
// logic so that it can be registered in the view engine collection
}
protected override IView CreatePartialView(ControllerContext
controllerContext, string partialPath)
{
var
physicalpath
=
controllerContext.HttpContext.Server.MapPath(partialPath);
MyCustomView obj = new MyCustomView(); // Custom view
engine class
obj.FolderPath = physicalpath; // set the path where the views will
be stored
return obj;
// returned this view paresing logic
// so that it can be registered in the view engine collection
}
}
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 that.
protected void Application_Start()
{
// Step3 :- register this object in the view engine collection
ViewEngines.Engines.Add(new MyViewEngineProvider());
..
}
Below is a simple output of the custom view written using the
commands defined at the top.
36) But WCF SOAP also does the same thing, so how does
WebAPI differ?
Size
Protocol
Formats
SOAP
Heavy weight because of
complicated
WSDL
structure.
Independent of protocols.
To parse SOAP message, the
client needs to understand
WSDL
format.
Writing
custom code for parsing
WSDL is a heavy duty task. If
your client is smart enough
to create proxy objects like
WEB API
Light weight, only the necessary
information is transferred.
Only for HTTP protocol
Output of WebAPI are simple string
messages, JSON, simple XML format,
etc. So writing parsing logic for that is
very easy.
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 the HTTP protocol.
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
Step 3: If you make an HTTP GET call you should get the below results:
Figure: HTTP
In BundleConfig.cs, add the JS files you want bundle into a single entity
in to the bundles collection. In the below code we are combining all the
javascript JS files which exist in the Scripts folder as a single unit in to
the bundle collection.
bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js"));
Below is how your BundleConfig.cs file will look like:
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js"));
BundleTable.EnableOptimizations = true;
}
}
Once you have combined your scripts into one single unit we then to
include all the JS files into the view using the below code. The below
code needs to be put in the ASPX or Razor view.
<%= Scripts.Render("~/Scripts/MyScripts") %>
If you now see your page requests you would see that script request is
combined into one request.
projects you will end up with 100s of controller classes making life hell
for maintenance.
You can add an area by right clicking on the MVC solution and clicking
on Area menu as shown in the below figure.
obj.Customer.Amount = 1000;
But when this Customer model object is displayed on the MVC view it
looks something as shown in the below figure. It has CustomerName
, Amount plus Customer Buying Level fields on the view / screen.
Customer buying Level is a color indicationwhich indicates how
aggressive the customer is buying.
Customer buying level color depends on the value of the Amount
property. If the amount is greater than 2000 then color is red , if
amount is greater than 1500 then color is orange or else the color is
yellow.
In other words Customer buying level is an extra property which is
calculated on the basis of amount.
Customer
Customer ViewModel
Model
CustomerName TxtCustomerName
Amount
TxtAmount
CustomerBuyingLevelColor
App initialization
Routing
Instantiate and execute controller
Locate and invoke controller action
Instantiate and render view
Used to register Web API routes, as well as set any additional Web API
configuration settings.
59) What are the default Top level directories created when
adding MVC4 application?
69) How can you define a dynamic property with the help of
viewbag in ASP.NET MVC?
Assign a key name with syntax, ViewBag.[Key]=[ Value] and value
using equal to operator.
For example, you need to assign list of students to the dynamic
Students property of ViewBag.
viewModel
new
return View(viewModel);
}
public ActionResult Create(CreateEmployeeViewModel viewModel)
{
{
RuleFor(x => x.FirstName)
.NotEmpty()
.WithMessage("First name required")
.Length(1, 50)
.WithMessage("First name must not be greater than 50
characters");
RuleFor(x => x.LastName)
.NotEmpty()
.WithMessage("Last name required")
.Length(1, 50)
.WithMessage("Last name must not be greater than 50
characters");
}
}
The key thing to remember is that the view model only represents the
data that you want use. You can imagine all the unneccessary code and
validation if you have a domain model with 30 properties and you only
want to update a single value. Given this scenario, you would only have
this one value/property in the view model and not the whole domain
object.
string y = ?because.?;
}
Aspx
<%
int x = 123;
string y = "because.";
%>
Namespace: System.Web.WebPages
Assembly: System.Web.WebPages.dll
}
Aspx
<% foreach (var item in items) { %>
<span>Item <%: item.Name %>.</span>
<% } %>
meaningful test driven code but will also reduce our controller code of
accessing data.
For group of views that all use the same layout, this can get a bit
redundant and harder to maintain.
The _ViewStart.cshtml page can be used to remove this redundancy.
The code within this file is executed before the code in any view placed
in the same directory. This file is also recursively applied to any view
within a subdirectory.
When we create a default ASP.NET MVC project, we find there is
already a _ViewStart .cshtml file in the Views directory. It specifies a
default layout:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
Because this code runs before any view, a view can override the Layout
property and choose a different one. If a set of views shares common
settings, the _ViewStart.cshtml file is a useful place to consolidate
these common view settings. If any view needs to override any of the
common settings, the view can set those values to another value.
Note: Some of the content has been taken from various books/articles.
helper we can use to build a robust form tag for our search form, but
without using lines and lines of code:
@using (Html.BeginForm("Search", "Home", FormMethod.Get)) {
<input type="text" name="q" />
<input type="submit" value="Search" />
}
</ul>
</div>
Other overloads of the ValidationSummary helper enable you to
provide header text and set specific HTML attributes.
NOTE: By convention, the ValidationSummary helper renders the CSS
class validation-summary-errors along with any specific CSS classes
you provide. The default MVC project template includes some styling
to display these items in red, which you can change in styles.css.
Contains classes and interfaces that support the MVC pattern for
ASP.NET Web applications. This namespace includes classes that
represent controllers, controller factories, action results, views, partial
views, and model binders.
System.Web.Mvc.Ajax namespace
Contains classes that support Ajax scripts in an ASP.NET MVC
application. The namespace includes support for Ajax scripts and Ajax
option settings.
System.Web.Mvc.Async namespace
Contains classes and interfaces that support asynchronous actions in
an ASP.NET MVC application.
System.Web.Mvc.Html namespace
Contains classes that help render HTML controls in an MVC
application. The namespace includes classes that support forms, input
controls, links, partial views, and validation.
route table. Route table is created when your web application first
starts. The route table is present in the Global.asax file.