You are on page 1of 15

FAQs

MVC-Day 01

1) What is MVC?
 MVC is a pattern which is used to split the application's implementation logic into three
components: models, views, and controllers.

2) Can you explain Model, Controller and View in MVC?


 Model – It’s a business entity and it is used to represent the application data.
 Controller – Request sent by the user always scatters through controller and it’s
responsibility is to redirect to the specific view using View() method.
 View – It’s the presentation layer of MVC.

3) Explain the new features added in version 4 of MVC (MVC4)?


Following are features added newly –
 Mobile templates
 Added ASP.NET Web API template for creating REST based services.
 Asynchronous controller task support.
 Bundling the java scripts.
 Segregating the configs for MVC routing, Web API, Bundle etc.

4) Can you explain the page life cycle of MVC?


Below are the processed followed in the sequence -
 App initialization
 Routing
 Instantiate and execute controller
 Locate and invoke controller action
 Instantiate and render view.

5) What are the advantages of MVC over ASP.NET?


 Provides a clean separation of concerns among UI (Presentation layer), model (Transfer
objects/Domain Objects/Entities) and Business Logic (Controller).
 Easy to UNIT Test.
 Improved reusability of model and views. We can have multiple views which can point to
the same model and vice versa.
 Improved structuring of the code.

6) What is Separation of Concerns in ASP.NET MVC?


 It’s is the process of breaking the program into various distinct features which overlaps in
functionality as little as possible. MVC pattern concerns on separating the content from
presentation and data-processing from content.

7) What is Razor View Engine?


Razor is the first major update to render HTML in MVC 3. Razor was designed specifically for
view engine syntax. Main focus of this would be to simplify and code-focused templating for
HTML generation. Below is the sample of using Razor:
@model MvcMusicStore.Models.Customer
@{ViewBag.Title = "Get Customers";}
<div class="cust"> <h3><em>@Model.CustomerName</em> </h3>

8) What is the use of ViewModel in MVC?


ViewModel is a plain class with properties, which is used to bind it to strongly typed view.
ViewModel can have the validation rules defined for its properties using data annotations.

9) What you mean by Routing in MVC?


Routing is a pattern matching mechanism of incoming requests to the URL patterns which are
registered in route table. Class – “UrlRoutingModule” is used for the same process
.
10) What are Actions in MVC?
Actions are the methods in Controller class which is responsible for returning the view or json
data. Action will mainly have return type – “ActionResult” and it will be invoked from method –
“InvokeAction()” called by controller.

11) Explain Bundle.Config in MVC4?


"BundleConfig.cs" in MVC4 is used to register the bundles by the bundling and minification
system. Many bundles are added by default including jQuery libraries like - jquery.validate,
Modernizr, and default CSS references.

12) How route table has been created in ASP.NET MVC?


Method – “RegisterRoutes()” is used for registering the routes which will be added in
“Application_Start()” method of global.asax file, which is fired when the application is loaded or
started.

13) Which are the important namespaces used in MVC?


Below are the important namespaces used in MVC -
System.Web.Mvc
System.Web.Mvc.Ajax
System.Web.Mvc.Html
System.Web.Mvc.Async

14) What are the components required to create a route in MVC?


 Name - This is the name of the route.
 URL Pattern – Placeholders will be given to match the request URL pattern.
 Defaults –When loading the application which controller, action to be loaded along with
the parameter.

15) What is RouteConfig.cs in MVC 4?


"RouteConfig.cs" holds the routing configuration for MVC. RouteConfig will be initialized on
Application_Start event registered in Global.asax.

MVC-Day-02

1) How can I return string result from Action in MVC?


Below is the code snippet to return string from action method –
public ActionResult TestAction() {
return Content("Hello Test !!");
}

2) How we can override the action names in MVC?


If we want to override the action names we can do like this –
[ActionName("NewActionName")]
public ActionResult TestAction() {
return View();
}

3) What is Razor View Engine?


Razor is a markup syntax that let you embed server side code (C#) into webpages. Server based
code can create dynamic web content on the fly, while a webpage is written to the browser.

4) Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web
application?
Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web
application.

5)What is the greatest advantage of using asp.net mvc over asp.net webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested

6) What is the role of a controller in an MVC application?


The controller responds to user interactions, with the application, by selecting the action method
to execute and alse selecting the view to render.

7) Where are the routing rules defined in an asp.net MVC application?


In Application_Start event in Global.asax

8) ASP.NET MVC application, makes use of settings at 2 places for routing to work
correctly. What are these 2 places?
1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the
Global.asax file.

9) What is ViewStart Page in MVC?


This page is used to make sure common layout page will be used for multiple views. Code
written in this file will be executed first when application is being loaded.

10) Explain the methods used to render the views in MVC?


Below are the methods used to render the views from action -
 View() – To return the view from action.
 PartialView() – To return the partial view from action.
 RedirectToAction() – To Redirect to different action which can be in same controller or
in different controller.
 Redirect() – Similar to “Response.Redirect()” in webforms, used to redirect to specified
URL.
 RedirectToRoute() – Redirect to action from the specified URL but URL in the route
table has been matched.

11) What are the sub types of ActionResult?


ActionResult is used to represent the action method result. Below are the subtypes of
ActionResult –
 ViewResult
 PartialViewResult
 RedirectToRouteResult
 RedirectResult
 JavascriptResult
 JSONResult
 FileResult
 HTTPStatusCodeResult

12) What are Non Action methods in MVC?


In MVC all public methods have been treated as Actions. So if you are creating a method and if
you do not want to use it as an action method then the method has to be decorated with
“NonAction” attribute as shown below –
[NonAction]
public void TestMethod()
{
// Method logic
}

13) How to change the action name in MVC?


“ActionName” attribute can be used for changing the action name. Below is the sample code
snippet to demonstrate more –
[ActionName("TestActionNew")]
public ActionResult TestAction()
{
return View();
}
So in the above code snippet “TestAction” is the original action name and in “ActionName”
attribute, name - “TestActionNew” is given. So the caller of this action method will use the name
“TestActionNew” to call this action.

14) What are Code Blocks in Views?


Unlike code expressions that are evaluated and sent to the response, it is the blocks of code that
are executed. This is useful for declaring variables which we may be required to be used later.
@{
int x = 123;
string y = "aa";
}

15) Can a view be shared across multiple controllers? If Yes, How we can do that?
Yes, we can share a view across multiple controllers. We can put the view in the “Shared” folder.
When we create a new MVC Project we can see the Layout page will be added in the shared
folder, which is because it is used by multiple child pages.
MVC-Day-03
1 ) Can we add constraints to the route? If yes, explain how we can do it?
Yes we can add constraints to route in following ways –
 Using Regular Expressions
 Using object which implements interface - IRouteConstraint.

2) What are the possible Razor view extensions?


Below are the two types of extensions razor view can have –
 .cshtml – In C# programming language this extension will be used.
 .vbhtml - In VB programming language this extension will be used.

3) What is the need of Action Filters in MVC?


Action Filters allow us to execute the code before or after action has been executed. This can be
done by decorating the action methods of controls with MVC attributes.

4) Mention some action filters which are used regularly in MVC?


Below are some action filters used –
 Authentication
 Authorization
 HandleError
 OutputCache

5) In Server how to check whether model has error or not in MVC?


Whenever validation fails it will be tracked in ModelState. By using property – IsValid it can be
determined. In Server code, check like this –
if(ModelState.IsValid){
// No Validation Errors
}
6) What are Model Binders in MVC?
For Model Binding we will use class called – “ModelBinders”, which gives access to all the
model binders in an application. We can create a custom model binders by inheriting
“IModelBinder”.

7) How we can handle the exception at controller level in MVC?


Exception Handling is made simple in MVC and it can be done by just overriding
“OnException” and set the result property of the filtercontext object (as shown below) to the
view detail, which is to be returned in case of exception.
protected overrides void OnException(ExceptionContext filterContext)
{
}
8) Does Tempdata hold the data for other request in MVC?
If Tempdata is assigned in the current request then it will be available for the current request and
the subsequent request and it depends whether data in TempData read or not. If data in Tempdata
is read then it would not be available for the subsequent requests.

9) Explain Keep method in Tempdata in MVC?


As explained above in case data in Tempdata has been read in current request only then “Keep”
method has been used to make it available for the subsequent request.
@TempData[“TestData”];
TempData.Keep(“TestData”);

10) Explain Peek method in Tempdata in MVC?


Similar to Keep method we have one more method called “Peek” which is used for the same
purpose. This method used to read data in Tempdata and it maintains the data for subsequent
request.
string A4str = TempData.Peek("TT").ToString();

11) What is ViewData?


Viewdata contains the key, value pairs as dictionary and this is derived from class –
“ViewDataDictionary“. In action method we are setting the value for viewdata and in view the
value will be fetched by typecasting.

12) What is the difference between ViewBag and ViewData in MVC?


 ViewBag is a wrapper around ViewData, which allows to create dynamic properties.
Advantage of viewbag over viewdata will be –
 In ViewBag no need to typecast the objects as in ViewData.
 ViewBag will take advantage of dynamic keyword which is introduced in version 4.0.
But before using ViewBag we have to keep in mind that ViewBag is slower than
ViewData.

13) Explain TempData in MVC?

 TempData is again a key, value pair as ViewData. This is derived from


“TempDataDictionary” class. TempData is used when the data is to be used in two
consecutive requests, this could be between the actions or between the controllers. This
requires typecasting in view.
14) What are HTML Helpers in MVC?
 HTML Helpers are like controls in traditional web forms. But HTML helpers are more
lightweight compared to web controls as it does not hold viewstate and events.
 HTML Helpers returns the HTML string which can be directly rendered to HTML page.
Custom HTML Helpers also can be created by overriding “HtmlHelper” class.

15) What is Layout in MVC?


Layout pages are similar to master pages in traditional web forms. This is used to set the
common look across multiple pages. In each child page we can find – /p>
@{
Layout = "~/Views/Shared/TestLayout1.cshtml";
}
This indicates child page uses TestLayout page as it’s master page.

16) Why to use Html.Partial in MVC?


This method is used to render the specified partial view as an HTML string. This method does
not depend on any action methods. We can use this like below –
@Html.Partial("TestPartialView")

17) What is Html.RenderPartial?


Result of the method – “RenderPartial” is directly written to the HTML response. This method
does not return anything (void). This method also does not depend on action methods.
RenderPartial() method calls “Write()” internally and we have to make sure that “RenderPartial”
method is enclosed in the bracket. Below is the sample code snippet –
@{Html.RenderPartial("TestPartialView"); }

19) What is PartialView in MVC?


PartialView is similar to UserControls in traditional web forms. For re-usability purpose partial
views are used. Since it’s been shared with multiple views these are kept in shared folder. Partial
Views can be rendered in following ways –
 Html.Partial()
 Html.RenderPartial()

20) How we can add the CSS in MVC?


Below is the sample code snippet to add css to razor views –
<link rel="StyleSheet" href="/@Href(~Content/Site.css")" type="text/css"/>

21) Can you explain RenderBody and RenderPage in MVC?


RenderBody is like ContentPlaceHolder in web forms. This will exist in layout page and it will
render the child pages/views. Layout page will have only one RenderBody() method.
RenderPage also exists in Layout page and multiple RenderPage() can be there in Layout page.

22) How we can multiple submit buttons in MVC?


Below is the scenario and the solution to solve multiple submit buttons issue.
Scenario –
@using (Html.BeginForm(“MyTestAction”,”MyTestController”)
{
<input type="submit" value="MySave" />
<input type="submit" value="MyEdit" />

}
Solution :
Public ActionResult MyTestAction(string submit) //submit will have value either “MySave” or
“MyEdit”
{
// Write code here

23) Explain what is the difference between View and Partial View?

View Partial View


 It contains the layout page  It does not contain the layout page
 Before any view is rendered,  Partial view does not verify for a
viewstart page is rendered viewstart.cshtml. We cannot put common
 View might have markup tags like code for a partial view within the
body, html, head, title, meta etc. viewStart.cshtml.page
 View is not lightweight as compare  Partial view is designed specially to
to Partial View render within the view and just because of
that it does not consist any mark up
 We can pass a regular view to the
RenderPartial method

MVC-Day-04

1) What is the use of action filters in an MVC application?


Action Filters allow us to add pre-action and post-action behavior to controller action methods.

2) If I have multiple filters impleted, what is the order in which these filters get executed?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters

3) What are the different types of filters, in an asp.net mvc application?


1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters

4) Give an example for Authorization filters in an asp.net mvc application?


1. RequireHttpsAttribute
2. AuthorizeAttribute

5) Which filter executes first in an asp.net mvc application?


Authorization filter

6) What are the levels at which filters can be applied in an asp.net mvc application?
1. Action Method
2. Controller
3. Application

7) What filters are executed in the end?


Exception Filter.

8) What type of filter does OutputCacheAttribute class represents?


Result Filter

9) What are the 2 popular asp.net mvc view engines?


1. Razor
2. .aspx

10) What symbol would you use to denote, the start of a code block in razor views?
@

11) What symbol would you use to denote, the start of a code block in aspx views?
<%= %>
12) In razor syntax, what is the escape sequence character for @ symbol?
The escape sequence character for @ symbol, is another @ symbol

13) When using razor views, do you have to take any special steps to proctect your asp.net
mvc application from cross site scripting (XSS) attacks?
No, by default content emitted using a @ block is automatically HTML encoded to protect from
cross site scripting (XSS) attacks.

14) When using aspx view engine, to have a consistent look and feel, across all pages of the
application, we can make use of asp.net master pages. What is asp.net master pages
equivalent, when using razor views?
To have a consistent look and feel when using razor views, we can make use of layout pages.
Layout pages, reside in the shared folder, and are named as _Layout.cshtml

15) What are child actions in MVC?


To create reusable widgets child actions are used and this will be embedded into the parent
views. In MVC Partial views are used to have reusability in the application. Child action mainly
returns the partial views.

16) How we can invoke child actions in MVC?


“ChildActionOnly” attribute is decorated over action methods to indicate that action method is a
child action. Below is the code snippet used to denote the child action –
[ChildActionOnly]
public ActionResult MenuBar()
{
//Logic here
return PartialView();
}

17) How do you specify comments using razor syntax?


Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the
end. An example is shown below.
@* This is a Comment *@
MVC-Day-05

1) What are Scaffold templates in MVC?


Scaffolding in ASP.NET MVC is used to generate the Controllers,Model and Views for create,
read, update, and delete (CRUD) functionality in an application. The scaffolding will be knowing
the naming conventions used for models and controllers and views.
2) Explain the types of Scaffoldings.
Below are the types of scaffoldings –
 Empty
 Create
 Delete
 Details
 Edit
 List

3) What is Area in MVC?


Area is used to store the details of the modules of our project. This is really helpful for big
applications, where controllers, views and models are all in main controller, view and model
folders and it is very difficult to manage.

4) How we can register the Area in MVC?


When we have created an area make sure this will be registered in “Application_Start” event
in Global.asax. Below is the code snippet where area registration is done –
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
}

5) What are Validation Annotations?

Data annotations are attributes which can be found in the


"System.ComponentModel.DataAnnotations" namespace. These attributes will be used for
server-side validation and client-side validation is also supported. Four attributes - Required,
String Length, Regular Expression and Range are used to cover the common validation
scenarios.

6) What are the different Data Annotation attributes ?


Ans : Following are the mostly used Data Annotation attributes :

 Required - This attribute makes the property of model mandatory for user.
 StringLength - The StringLength attribute specifies the maximum length of string that is
acceptable.
 RegularExpression - Regular expressions are an efficient and terse means to enforce the
shape and contents of a string value.
 Range - The Range attribute specified the minimum and maximum constraints for a
numerical value.
 Compare - The compare attribute ensures two properties on a model object have the
same value.
 Display - The Display attribute sets the friendly name for a model property.
 ScaffoldColumn - The scaffoldColumn attribute hides a property from HTML helper
such as EditorForModel and DisplayForModel.
 MaxLength - MaxLength Attribute ensures the length of the string entered is according
to the specified value.
 DataType - The DataType attribute enables you to provide the run time with information
about the specific purpose of a property.
 UIHint - The UIHint attribute as the name itself suggest gives the Asp.net MVC run time
the name of a template to use when rendering output with the templated helpers like
(DisplayFor and EditorFor).
 HiddenInput - The property that has HiddenInput defined on it will be rendered as input
type hidden on form.

7) What is Entity Framework?

Entity Framework is an ORM from Microsoft that will enable the developers to work with
domain specific objects, which eliminates the extra code being written in the data access layer.

8) What are the advantages of using Entity Framework?


Main advantages of Entity Framework are:

 Separation of Concerns (SoC).


 LINQ is used as a common syntax for all object queries.
 Code Auto-Generation.

9) Why to use Entity Framework?


Writing ADO.NET code and managing it is a tedious job. To avoid this, Microsoft has provided
a solution - Entity Framework. Entity Framework reduces a great deal of code by enabling to
work with relational data as domain specific objects.

10) What is the difference between Entity Framework and ADO.NET?

ADO.NET Entity Framework

ADO.NET is faster. "Entity Framework will be around the ADO.NET, which means
ADO.NET Entity Framework

ADO.NET is faster than Entity Framework."

We need to write so much code Easy to use. As an Entity Framework will talk to database
to talk to database. without much code involved.

Performance is better than Entity


Performance is not good compared to ADO.NET.
Framework.

11) How to create Entity Data Model (EDM)?

Add New Item -> ADO.NET Entity Data Model, which generates file with .edmx extension.

12) What does .edmx consists of?

.edmx file is a XML file and it has Conceptual Model, Storage Model and Mapping details i.e,

 SSDL (Store schema definition language)


 CSDL (Conceptual schema definition language)
 MSL (Mapping specification language)

13) What is Conceptual Model?

Conceptual Models are the model classes which contain the relationships. These are independent
of the database design.

14 What is Storage Model?

Storage Models are our database design models, which contains database tables, views, stored
procs and keys with relationships.

15) What is Mapping?

The Mapping will have the information on how the Conceptual Models are mapped to Storage
Models.

17) What is the role of DB Context?

DBContext will be responsible for Insert, Update and Delete functionalities of


the entities. It acts like a bridge between the database and entity classes.
LAB TASK

MVC-Day-01

1.Create MVC Application Student Portal With Two Action Methods for showing Login Page
And Register Page(Mode l+ View)
2.Display Student details from Controller to View Using ViewBag And ViewData(Name
,Mobile, Age, Dept)
3.Display Student Details using Model Class(Model+View + Controller)

MVC -DAY-02

1. Create Employee Salary Calculation Application with Show Details, Salary Calculation
Action Methods using model,View and Controller
2. Design View Using HTML Contols to Get Employee details from Runtime
3. Design View Using HTML Helper Class Methods to Get Employee details from Runtime

MVC-Day-03

1. Create application to get Number from runtime and perform Mathematical Operations
a. Oddoreven
b. Prime or Not
c. Perfect Number
Choose option and click Submit button provide corresponding output.

2. Create application to get String from runtime and perform Mathematical Operations
a. S
b. Prime or Not
c. Perfect Number
Choose option and click Submit button provide corresponding output.

You might also like