What do you know about MVC?
MVC Stands for Model-View-Controller. MVC is a software architecture pattern for developing web application. It’s an application design model comprised of three interconnected parts. They include the model (data), the view (user interface), and the controller (processes that handle input).
Below is a description of each aspect of MVC:
- Model : A model is data used by a program. This may be a database, file, or a simple object, such as an icon or a character in a video game.
- View : A view is the means of displaying objects within an application. Examples include displaying a window or buttons or text within a window. It includes anything that the user can see.
- Controller : A controller updates both models and views. It accepts input and performs the corresponding update. For example, a controller can update a model by changing the attributes of a character in a video game. It may modify the view by displaying the updated character in the game.
What is a MVVM pattern? And Explain?
MVVM stands for Model-View-View Model. It supports two-way data binding between view and View model. This enables automatic propagation of changes, within the state of view model to the View. Typically, the view model uses the observer pattern to notify changes in the view model to model.
- Model : It represents a set of classes that describes the business logic and data. It also defines business rules for data means how the data can be changed and manipulated.
- View : It represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the controller as the result. This also transforms the model(s) into UI.
- View Model : It is responsible for exposing methods, commands, and other properties that helps to maintain the state of the view, manipulate the model as the result of actions on the view, and trigg”]er events in the view itself.
Can you tell me the different return types of a controller action method?
ViewResult: Renders a specified view to the response stream
PartialViewResult: Returns HTML from partial view
EmptyResult: empty response or No response
JsonResult: Serializes a given View Data object to JSON format
JavaScriptResult: Returns a piece of JavaScript code that can be executed on the client
ContentResult: Writes content to the response stream without requiring a view
RedirectResult: Performs an HTTP redirection to a specified or new URL
RedirectToRouteResult: Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
FileContentResult / FileStreamResult / FilePathResult : Represents the content of file
What are the pros of MVC?
- Multiple view support: Because of the separation of the model from the view, the user interface can display multiple views of the same data and at the same time.
- Change Accommodation: User interfaces tend to change more frequently than business rules.
- Separation of Concerns: Separation of Concerns is one of the core advantages of ASP.NET MVC. The MVC framework provides a clean separation of the UI, Business Logic, Model or Data.
- More Control: The ASP.NET MVC framework provides more control over HTML, JavaScript, and CSS than the traditional Webworm’s.
- Testability: This framework provides better testability of the Web Application and good support for the test-driven development too.
- Lightweight: MVC framework doesn’t use View State and that reduces the bandwidth of the requests to an extent.
- SEO-friendly development: The platform of MVC can support SEO-friendly development of web pages or web applications.
What are the different MVC components?
- Presentation: This component takes care of the visual representation of a particular abstraction in the application.
- Control: This component takes care of the consistency and uniformity between the abstraction within the system along with their presentation to the user. It is also responsible for communicating with all other controls within the MVC system.
- Abstraction: This component deals with the functionality of the business domain within the application.
Can you explain Partial View in MVC?
A partial view is a chunk of HTML that can be safely inserted into an existing DOM. Most commonly, partial views are used to componentize Razor views and make them easier to build and update. It can also be returned directly from controller methods. In this case, the browser still receives text/HTML content but not necessarily HTML content that makes up an entire page. As a result, if a URL that returns a partial view is directly invoked from the address bar of a browser, an incomplete page may be displayed. This may be something like a page that misses title, script and style sheets.
Can you explain the different properties of MVC routes?
- Route Name: It is the URL pattern which is used for mapping the handler.
- URL Pattern: A URL pattern can contain literal values and variable placeholders (referred to as URL parameters). The literals and placeholders are located in segments of the URL that are delimited by the slash (/) character.
- Defaults: This is the default parameter value assigned at the time of parameter creation.
- Constraints: A set of constraints to apply against the URL pattern to more narrowly define the URL that it matches.
What is difference between Routing and URL Rewriting?
Many developers compare routing to URL rewriting since both look similar and can be used to make SEO friendly URLs. But both the approaches are very much different. The main difference between routing and url rewriting is given below:
- URL rewriting is focused on mapping one URL (new url) to another URL (old url) while routing is focused on mapping a URL to a resource.
- URL rewriting rewrites your old url to new one while routing never rewrite your old url to new one but it maps to the original route.
Can you explain Route Constraints in MVC?
Routing is a great feature of MVC, it provides a REST based URL that is very easy to remember and improves page ranking in search engines.
Creating Route Constraints
Suppose we have defined the following route in our application and you want to restrict the incoming request url with numeric id only. Now let’s see how to do it with the help of regular expression.
public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // Route Pattern new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Default values for parameters ); } Restrict to numeric id only public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // Route Pattern new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Default values for parameters new { id = @"\d+" } //Restriction for id ); }
Now for this route, routing engine will consider only those URLs which have only numeric id like as http://example.com/Admin/Product/1 else it will consider that url is not matched with this route.
Can you explain namespaces in ASP.NET MVC?
- Web.Mvc : This Namespace contains classes, interfaces that support the MVC Pattern for ASP.NET web application. The namespaces include classes that represent controllers, controller factories, action result, views, partial views and model binders and much more.
- Web.Mvc.Html : This namespace contains the classes that help render HTML controls in MVC application. This include classes that support forms input controls, partial views, links and validation.
- Web.Mvc.Ajax : This namespace contains classes that support Ajax scripts in ASP.NET MVC application. This namespace includes supports for Ajax settings and Ajax Scripts as well.
- Web.Mvc.Asnc : This namespace contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application
Can you explain View Engine and How View Engine works?
A View Engine is a MVC subsystem which has its own markup syntax. It is responsible for converting server- side template into HTML markup and rendering it to the browser. Initially, ASP.NET MVC ships with one view engine, web forms (ASPX) and from ASP.NET MVC3 a new view engine, Razor is introduced. With ASP.NET MVC, you can also use other view engines like Spark, NHaml etc.
Each view engine has following three main components:
- ViewEngine class – This class implements the IViewEngine interface and responsible for locating view templates.
- View class – This class implements the IView interface and responsible for combining the template with data from the current context and convert it to output HTML markup.
- Template parsing engine – This parse the template and compiles the view into executable code.
For more:
Can you explain ViewStart and When to Use it?
_ViewStart.cshml page is used to serve common layout page(s) for a group of views. 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. ViewStart is executed at the very beginning followed by the start rendering as well as other views.
@ { Layout = "~/ Views/ Shared/ _ file.cshtml"; } <html> <head> <meta name="viewport" /> <title> InitialView </title> </head> <body> …. </body> </html>
When a set of views shares common settings, the _ViewStart.cshtml file is a great place to put these
common view settings. If any view needs to override any of the common settings then that view can set new values to common settings.
Can you explain RenderBody and RenderPage in MVC?
RenderBody method exists in the Layout page to render child page/view. It is just like the Content Place Holder on master page. A layout page can have only one RenderBody method.
<body> @RenderBody() @RenderPage("~/Views/Shared/_Header.cshtml") @RenderPage("~/Views/Shared/_Footer.cshtml") @RenderSection("scripts",false) @section scripts{ <script src="~/Scripts/jquery-1.7.1.min.js"></script> } </body>
RenderPage method also exists in the Layout page to render other page exists in your application. A layout page can have multiple RenderPage method.
@RenderPage("~/Views/Shared/_Header.cshtml")
Can you explain the methods used to render the views in MVC?
- 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.
Can you explain TempData in MVC?
TempData can be defined as a dictionary object used for storing data for a short period of time. Its 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 and it has the ability to preserve data for an HTTP request.
TempDataDictionary is inherited from the IDictionary<string, object>, ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>> and IEnumerable interfaces.
Example
public ActionResult FirstRequest() { List < string > TempDataTest = new List < string > (); TempDataTest.Add("Tejas"); TempDataTest.Add("Jignesh"); TempDataTest.Add("Rakesh"); TempData["EmpName"] = TempDataTest; return View(); } public ActionResult ConsecutiveRequest() { List < string > modelData = TempData["EmpName"] as List < string > ; TempData.Keep(); return View(modelData); }
Can you explain the use of Keep and Peek in TempData?
Once “TempData” is read in the current request, it’s not available in the subsequent request. If we want “TempData” to be read and also available in the subsequent request then after reading we need to call “Keep” method as shown in the code below.
@TempData["interviewgigdata"]; TempData.Keep("interviewgigdata");
The more shortcut way of achieving the same is by using “Peek”. This function helps to read as well advices MVC to maintain “TempData” for the subsequent request.
string str = TempData.Peek("Td").ToString();
What is the difference between Temp data, View, and View Bag?
ViewData
- ViewData is used to pass data from controller to view.
- It is derived from ViewDataDictionary class.
- It is available for the current request only.
- Requires typecasting for complex data types and checks for null values to avoid an error.
- If redirection occurs, then its value becomes null.
ViewBag
- ViewBag is also used to pass data from the controller to the respective view.
- ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
- It is also available for the current request only.
- If redirection occurs, then its value becomes null.
- It doesn’t require typecasting for the complex data type.
TempData
- TempData is derived from TempDataDictionary class
- TempData is used to pass data from the current request to the next request
- It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
- It requires typecasting for complex data types and checks for null values to avoid an error. Generally, it is used to store only one-time messages like the error messages and validation messages
What are the different types of Filters in MVC?
- Action Filters – Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter.
- Authorization Filters – Authorization filters are used to implement authentication and authorization for controller actions.
- Result Filters – Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
- Exception Filters – Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You can also use exception filters to log errors.
Can you explain Razor View Engine?
Razor is the first major update to render HTML in MVC 4. Razor was designed specifically for view engine syntax. Main focus of this would be to simplify and code-focused templating for HTML generation.
Razor is not a new programming language itself, but uses C# syntax for embedding code in a page without the ASP.NET delimiters: <%= %>. It is a simple-syntax view engine and was released as part of ASP.NET MVC 3. The Razor file extension is “cshtml” for the C# language. It supports TDD (Test Driven Development) because it does not depend on the System.Web.UI.Page class.
sample of using Razor:
@model MvcMusicStore.Models.Customer @{ViewBag.Title = “Get Customers”;} <div class=”cust”> <h3><em>@Model.CustomerName</em> </h3>
What are the possible file extensions used for razor views?
- .cshtml: When your MVC application is using C# as the programming language.
- .vbhtml: When your MVC application is using VB is the programming language.
What are the rules of Razor syntax?
- Razor code blocks are enclosed in @{ … }
- Inline expressions (variables and functions) start with @
- Variables are declared with the var keyword
- Strings are enclosed with quotation marks
- C# code is case sensitive
- C# files have the extension .cshtml
- Razor code statements are terminated with a semicolon