What is MVC?
MVC is a pattern which is used to split the application’s implementation logic into three components: models, views, and controllers. This pattern has been heralded by many developers as a useful pattern for reuse components of object code and a pattern that allows them to siginifically reduce the time it takes to develop web applications with user interfaces (UI).
Can you explain Model, Controller and View in MVC?
Model: It’s a business entity and it is used to represent the application data. This can represent either the data that is being transferred between the View and Controller components or any other business logic related data.
View: It’s the presentation layer of MVC. It is a pure HTML, which decides how the UI is going to look like.
Controller: Controllers act as an interface between Model and View components to process all the business logic and incoming requests, manipulate data using the Model component and interact with the Views to render the final output.
What is ASP.Net MVC?
The ASP.net MVC is a framework that provides an alternative to the ASP.Net web forms pattern creating web applications.
What are the new features in version 5 of MVC5?
- Only one ASP.Net experience
- Authentication filters
- Filter overrides
- ASP.Net identity
- Bootstarp
- Attribute Routing
What are the new features in version 4 of MVC (MVC4)?
- Mobile templates
- Asynchronous controller task support
- Bundling the java scripts
- Added ASP.NET Web API template for creating REST based services
- Segregating the configurations for MVC routing, Web API, Bundle etc
What are the steps in MVC page life cycle?
Step 1: Routing
Step 2: The URL Routing Module intercepts the request.
Step 3: MVC handles Executes
Step 4: The controller executes
Step 5: Render view method
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
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.
Can you explain ASP.Net Request MVC lifecycle?
When the user sends from the browser, it’s been handled by Routing concept and which navigates it to the appropriate Controller where controller picks up the relevant View and send it as a response to the User.
Routing: Asp.net Routing is the first step in MVC request cycle.
MvcHandler: The MvcHandler is responsible for initiating the real processing inside ASP.NET MVC. MVC handler implements IHttpHandler interface and further process the request by using ProcessRequest method
Action Execution: After the particular controller gets instantiated ActionInvoker determines which specific Action method needs to be execute. ActionInvoker uses ActionNameSelectorAttribute and ActionMethodSelectorAttribute to select Action method for execution
Rendor View Result: The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type
View Engine: The first step in the execution of the View Result involves the selection of the appropriate View Engine to render the View Result. It is handled by IViewEngine interface of the view engine. By default Asp.Net MVC uses WebForm and Razor view engines.
View: Action method may returns a text string, a binary file or a JSON data or javascript formatted data. The most important Action Result is the ViewResult, which renders and returns an HTML page to the browser by using the current view engine.
Can you explain View Model in MVC?
View Model is a plain class with properties, which is used to bind it to strongly typed view. View Model can have the validation rules defined for its properties using data annotations.
Can you explain 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.
Can you explain 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>
What is the extension of Razor View file?
.cshtml (for c#) and .vbhtml (for vb)
What is the meaning of Unobtrusive JavaScript?
This is a general term that conveys a general philosophy, similar to the term REST (Representational State Transfer). Unobtrusive JavaScript doesn’t intermix JavaScript code in your page markup.
Eg: Instead of using events like on click and on submit, the unobtrusive JavaScript attaches to elements by their ID or class based on the HTML5 data- attributes.
Can you explain HTML Helpers in ASP.Net 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 view state 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.
Can you explain 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.
Can you explain Controller in MVC?
Create a simple class and extend it from Controller class. The bare minimum requirement for a class to become a controller is to inherit it from ControllerBase is the class that is required to inherit to create the controller but Controller class inherits from ControllerBase.
Can you explain Attribute Routing in MVC?
ASP.NET Web API supports this type routing. This is introduced in MVC5. In this type of routing, attributes are being used to define the routes. This type of routing gives more control over classic URI Routing. Attribute Routing can be defined at controller level or at Action level like –
[Route(“{action = TestCategoryList}”)] - Controller Level
[Route(“customers/{TestCategoryId:int:min(10)}”)] - Action Level
How to enable Attribute Routing?
Just add the method – “MapMvcAttributeRoutes()” to enable attribute routing as shown below
public static void RegistearRoutes(RouteCollection routes)
{
routes.IgnoareRoute("{resource}.axd/{*pathInfo}");
//enabling attribute routing
routes.MapMvcAttributeRoutes();
//convention-based routing
routes.MapRoute
(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Customer", action = "GetCustomerList", id = UrlParameter.Optional }
);
}
Can you explain Dependency Resolution?
Dependency Resolver again has been introduced in MVC3 and it is greatly simplified the use of dependency injection in your applications. This turn to be easier and useful for decoupling the application components and making them easier to test and more configurable.
Can you explain the advantages of Dependency Injection?
Advantages of Dependency Injection (DI) in ASP.Net MVC
- Increases code reusing
- Reduces class coupling
- Improves application testing
- Improves code maintainability
For More:
Can you define Razor?
The Razor is the new View engine introduced in MVC 3.0.The View engine is responsible for processing the view files [e.g. .aspx, .cshtml] in order to generate HTML response. The previous versions of MVC were dependent on ASPX view engine.
What are the tools used for unit testing in ASP.Net MVC?
Some tools used for unitesting
MUnit
xUnit.Net
MoQ
Ninject 2
Can you explain JSON Binding?
JSON (JavaScript Object Notation) binding support started from MVC3 onwards via the newJsonValueProviderFactory, which allows the action methods to accept and model-bind data in JSON format. This is useful in Ajax scenarios like client templates and data binding that need to post data back to the server.
Can you 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.
E
Explain 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.
List out some important namespaces used in MVC?
System.Web.Mvc
System.Web.Mvc.Ajax
System.Web.Mvc.Html
System.Web.Mvc.Async
Can you explain 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.
What is the difference between ViewBag and ViewData in MVC?
View Bag is a wrapper around ViewData, which allows to create dynamic properties. Advantage of view bag 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 View Data.
Write a code return string result from Action in ASP.Net MVC?
By using, below code
Public ActionResult TestAction(){
Return Content (“Hello World!!”);
}
Can you explain Peek method in Tempdata?
In Asp.Net 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();
What are routs in MVC and where to configure it?
Routing is a way to process the incoming url that is more descriptive and give desired response. A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as a .aspx file in a Web Forms application. A handler can also be a class that processes the request, such as a controller in an MVC application. To define a route, you create an instance of the Route class by specifying the URL pattern, the handler, and optionally a name for the route.
What is AuthConfig.cs in MVC4?
AuthConfig.cs is used to configure security settings, including sites for OAuth login.
What is the default Form method (i.e. GET, POST) for an action method
GET. To change this you can add an action level attribute e.g [HttpPost]
Explain Keep method in Tempdata in ASP.Net 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”);
What is Partial View in ASP.Net 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()
Write a sample code CSS in ASP.Net MVC?
Below is the sample code snippet to add css to razor views :
< link rel="StyleSheet" href="/@Href(~Content/Site.css")" type="text/css"/>
What is difference between Web Forms and MVC?
MVC uses Front Controller approach which means there is a common controller for all pages instead of every page having its own controller like in Web Forms which uses code-behind file that will process the request.
MVC architecture has a very clean separation of concern between Controllers, Models and Views unlike Web Forms.
MVC application applies a approach which is stateless as per common HTTP convention different from Web Forms which use View State.
Development of a MVC application requires a better and detailed knowledge of JavaScript, HTML and CSS.
Absence of Life Cycle in MVC leads to a simpler request cycle which reduces load times MVC does not follow the RAD (Rapid Application Development) approach which may slow down development for people but it is better for Custom Application as developer has more Control over the code.
MVC is a recommended approach for Larger Application development where multiple teams are working in conjunction.
What is the 'HelperPage.IsAjax' Property?
The HelperPage.IsAjax property gets a value that indicates whether Ajax is being used during the request of the Web page.
Can you explain Bundling and Minification in MVC?
Bundling and minification are two techniques you can use to improve request load time. Bundling helps you to download files of same type using one request instead of multiple requests. This way you can download styles and scripts using less requests than it takes to request all files separately.
Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary white space, comments and shortening variable names to one character.
Can I set the unlimited length for ‘maxjsonlength’ property in config?
No. We can’t set unlimited length for property maxJsonLength. Default value is – 102400 and maximum value what we can set would be : 2147483644.
Can you explain Scaffolding in MVC?
Scaffolding in MVC is used to auto-generate CRUD code in MVC template.
Where CRUD stands for Create, Read, Update and Delete.
Why to use “(resource).axd/(*pathinfo)” in Routing in ASP.NET MVC?
Using this default route – {resource}.axd/{*pathInfo}, we can prevent the requests for the web resources files like – WebResource.axd or ScriptResource.axd from passing to a controller.
Can you explain the methods used to render the views in ASP.NET 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.