MVC
is a framework methodology that divides an application’s implementation
into three component roles: models, views, and controllers.
What does Model, View and Controller represent in an MVC application?
Model: represents the application data domain. In short the applications business logic is contained with in the model.
Model: represents the application data domain. In short the applications business logic is contained with in the model.
View: represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.
Controller: is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.
What is the ‘page lifecycle’ of an ASP.NET MVC?
Any web application has two main execution steps, first understanding the request and depending on the type of the request sending out appropriate response.
Creating the request object:
The request object creation has four major steps. The following is the detailed explanation of the same.
Step 1: Fill routeMVC 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.
Step 2: Fetch route
Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.
Step 3: Request context created
The “RouteData” object is used to create the “RequestContext” object.
Step 4: Controller instance created
This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.
Creating Response object
This phase has two steps executing the action and finally sending the response as a result to the view.
Following process are performed by ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view
What does the Web.Config file do in the views folder of a MVC project?
The web.config in the Views directory just has one significant entry, which blocks direct access:
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
This is so someone cannot manually try to go to http://www.yoursite.com/views/main/index.aspx and load the page outside the MVC pipeline.
ViewModel : is a “Model of the View” meaning it is an abstraction of the View that also serves in data binding between the View and the Model.
ViewModel acts as a data binder/converter that changes Model information into View information and passes commands from the View into the Model. The ViewModel exposes public properties, commands, and abstractions.
to know more about Click here
What's the base class of a Razor View in ASP.NET MVC?
System.Web.Mvc.WebViewPage
Test Driven Development is the process where the developer creates the test case first and then fixes the actual implementation of the method. It happens this way, first create a test case, fail it, do the implementation, ensure the test case success, re-factor the code and then continue with the cycle again.
What is Asynchronous Programming ?
Asynchronous Programming means parallel programming. By using Asynchronous Programming, the compiler can execute multiple functions/methods at same time without blocking any function/method.
Async keyword is used to call the function/method as asynchronously.
Await keyword is used when we need to get result of any function/method without blocking that function/method.
public async Task<string> GetNameAndContent()
{
var nameTask = GetLongRunningName(); //This method is asynchronous
var content = GetContent(); //This method is synchronous
var name = await nameTask;
return name + ": " + content;
}
What is the greatest advantage of using asp.net mvc over asp.net webforms?
The main advantages of ASP.net MVC are:
- Enables the full control over the rendered HTML.
- Provides clean separation of concerns(SoC).
- Enables Test Driven Development (TDD).
- it is difficult to unit test UI with webforms, where Views in mvc can be easily unit tested.
- Easy integration with JavaScript frameworks.Following the design of stateless nature of the web.
- RESTful urls that enables SEO.
- No ViewState and PostBack events
- SEO friendly
- Complex applications can be easily managed
The MVC separation helps you manage complex applications, because you can focus on one aspect a time. For example, you can focus on the view without depending on the business logic. It also makes it easier to test an application.
The main advantage of ASP.net Web Form are:
Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?
The main advantage of ASP.net Web Form are:
- It provides RAD development
- Easy development model for developers those coming from winform development.
Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.
ASP.NET MVC 4 Features:
Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load performance.
Minification[MVC4]:
Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary white space and comments and shortening variable names to one character.
Display Modes[MVC4]:
The new Display Modes feature lets an application select views depending on the browser that's making the request. For example, if a desktop browser requests the Home page, the application might use the Views\Home\Index.cshtml template. If a mobile browser requests the Home page, the application might return the Views\Home\Index.mobile.cshtml template.
Controlling Bundling and Minification
Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element in the Web.config file. In the following XML, debug is set to true so bundling and minification is disabled.
Is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.
Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax
Name a few different return types of a controller action method?
- ASP.NET Web API
- Refreshed and modernized default project templates
- New mobile project template
- Many new features to support mobile apps
- Display Modes
- Bundling and Minification
- Enabling Logins from Facebook and Other Sites Using OAuth and OpenID
Bundling is a new feature in ASP.NET 4.5 that makes it easy to combine or bundle multiple files into a single file. You can create CSS, JavaScript and other bundles. Fewer files means fewer HTTP requests and that can improve first page load performance.
Minification[MVC4]:
Minification performs a variety of different code optimizations to scripts or css, such as removing unnecessary white space and comments and shortening variable names to one character.
Display Modes[MVC4]:
The new Display Modes feature lets an application select views depending on the browser that's making the request. For example, if a desktop browser requests the Home page, the application might use the Views\Home\Index.cshtml template. If a mobile browser requests the Home page, the application might return the Views\Home\Index.mobile.cshtml template.
Controlling Bundling and Minification
Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element in the Web.config file. In the following XML, debug is set to true so bundling and minification is disabled.
<system.web>
<compilation debug="true" />
<!-- Lines removed for clarity. -->
</system.web>
To enable bundling and minification, set the
debug
value to "false". You can override the Web.config setting with the EnableOptimizations
property on the BundleTable
class. The following code enables bundling and minification and overrides any setting in the Web.config file.public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); // Code removed for clarity. BundleTable.EnableOptimizations = true; }for more info about this Topic follow the Link MVC-4/Bundling-and-Minification
Is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.
Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax
Name a few different return types of a controller action method?
There 12 kinds of results in MVC, at the top is “ActionResult”class which is a base class that can have 11 subtypes’s as listed below: -
- ViewResult - Renders a specified view to the response stream
- PartialViewResult - Renders a specified partial view to the response stream
- EmptyResult - An empty response is returned
- RedirectResult - Performs an HTTP redirection to a specified URL
- RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
- JsonResult - Serializes a given ViewData 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
- FileContentResult -Returns a file to the client
- FileStreamResult - Returns a file to the client, which is provided by a Stream
- FilePathResult - Returns a file to the client
What is the difference between ViewResult() and ActionResult() in ASP.NET MVC?
- ActionResult is an abstract class.
- ViewResult derives from ActionResult. Other derived classes include JsonResult and PartialViewResult.
- The View() method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could change the method body to conditionally return a RedirectResult or something else without changing the method definition.
public ActionResult Foo()
{
if (1==2)
return View(); // returns ViewResult
else
return Json(new { foo = "bar", baz = "Blech" }, JsonRequestBehavior.AllowGet); // returns JsonResult
}
DIFFERENCE BETWEEN @Html.TextBox and @Html.TextBoxFor
Html.TextBox is not strongly typed and it doesn't require a strongly typed view meaning that you can hardcode whatever name you want as first argument and provide it a value:
@Html.TextBox("foo",
"some value")
You can set some value in the ViewData dictionary inside the controller action and the helper will use this value when rendering the textbox (ViewData["foo"] = "bar").
Html.TextBoxFor is requires a strongly typed view and uses the view model:
@Html.TextBoxFor(x => x.Foo)
And because it is a good practice to use strongly typed views and view models you should always use the Html.TextBoxFor helper.
What is AntiForgeryToken() in MVC?
Generates a hidden form field (anti-forgery token) that is validated when the form is submitted.
The anti-forgery token can be used to help protect your application against cross-site request forgery. To use this feature, call the AntiForgeryToken method from a form and add the ValidateAntiForgeryTokenAttribute attribute to the action method that you want to protect.
to know more Click here
What is the significance of ASP.NET routing?
Routing is a URL Pattern that Maps incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.
There are two types of routing (after the introduction of ASP.NET MVC 5).
Convention based routing: to define this type of routing, we call MapRoute method and set its unique name, url pattern and specify some default values.
Attribute based routing: to define this type of routing, we specify the Route attribute in the action method of the controller.
Route constraints MVC5
We can also specify parameter constraints placing the constraint name after the parameter name separated by colon. For example we can specify that the parameter type should be integer by using the following
[Route("User/Profile/{id:int}")]
Now if we do not specify integer parameter then the route will not match even if other segments match.
Route Prefix - MVC5
If we have multiple action methods in a controller all using the same prefix we can use RoutePrefix attribute on the controller instead of putting that prefix on every action method.
Like we can attach the following attribute on the controller
[RoutePrefix("User")]
So now our Route attribute on our action method does not need to specify the common prefix
[Route("Profile/{id}")]
How route table is created in ASP.NET MVC?
When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.
Attribute based routing in MVC5
Using attribute based routing we can define the route in the same place where action method is defined. Following is an example of a route defined using the Route attribute.
[Route("User/Profile/{id}")]
public ActionResult GetUserProfile(string id)
{
ViewBag.Id = id;
return View();
}
To enable attribute based routing we need to add the following in the RouteConfig file.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
}
Optional Parameter in URL- MVC5
We can also specify if there is any optional parameter in the URL pattern defined by the Route attribute with the “?” character. If the above action method is called and the value for “id” parameter is not provided we will get an exception since id is a required parameter. We can make it an optional parameter by making the following changes.
[Route("User/Profile/{id?}")]
public ActionResult GetUserProfile(int? id)
{
ViewBag.Id = id; return View();
}
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.
Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax
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.
Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax
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.
Action Filters allow us to add pre-action and post-action behavior to controller action methods.
If I have multiple filters implemented, what is the order in which these filters get executed?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters
Follow the link for more: filters-in-Asp-Net-mvc-5-0
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters
Follow the link for more: filters-in-Asp-Net-mvc-5-0
Action Filters
There
are a set of Action filters available with ASP.NET MVC 3 to filter
actions. Action filters are defined as attributes and applied to an
Action or controller.
1. Authorize
Authorize
filters ensure that the corresponding Action will be called by an
authorized user only. If the user is not authorized, he will be
redirected to the login page.
[Authorize]
public ActionResult About()
{
return View();
}
2. HandleError
HandleError will handle the various exceptions thrown by the application and display user friendly message to the user. By default, this filter is registered in Global.asax.
1. RequireHttps Attribute
2. Authorize Attribute
Some Important points:
- AuthorizeAttribute inherits from FilterAttribute, IAuthorizationFilter.
- OnActionExecuting, OnActionExecuted defines in IActionFilter interface
- OnResultExecuting, OnResultExecuted defines in IResultFilter interface
- OnException defines in IExceptionFilter interface
- OnAuthorization defines IAuthorizationFilter interface
- ViewBag, ViewData, TempData defines in ControllerBase class.
- HandleError inherits from HandleErrorAttribute that inherits FilterAttribute, IExceptionFilter
ASP.NET MVC 3 defines a set of Action selectors which determine the selection of an Action. One of them is
ActionName
,
used for defining an alias for an Action. When we define an alias for
an Action, the Action will be invoked using only the alias; not with the
Action name.[ActionName("NewAbout")]
public ActionResult About()
{
return Content("Hello from New About");
}
System.Web.Mvc
What is Razor View Engine?
Razor view engine is a new view engine created with ASP.Net MVC. It allows us to write Compact, Expressive, Clean and Fluid code with new syntaxes to include server side code in to HTML. Razor uses @ symbol to make the code.
What is difference between Viewbag and Viewdata in ASP.NET MVC?
The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.
ViewData requires typecasting for complex data type and check for null values to avoid error.ViewBag doesn’t require typecasting for complex data type.
ViewData and ViewBag are used to pass data from controller to corresponding view.
Difference between tempdata , viewdata and viewbag
View data: - Helps to maintain data when you move from controller to view.
View Bag: - It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is not required. It uses the dynamic keyword internally.
Below is a summary table which shows different mechanism of persistence.
Maintains data between ViewData/ViewBag ,TempData, Hidden fields,Session
ViewData/ViewBag TempData Hidden fields Session
Controller to Controller No Yes No Yes
Controller to View Yes No No Yes
View to Controller No No Yes Yes
Partial View: A partial view is like as user control in Asp.Net Web forms that is used for code re-usability. Partial views helps us to reduce code duplication. Hence partial views are reusable views like as Header and Footer views. We can use partial view to display blog comments, product category, social bookmarks buttons, a dynamic ticker, calendar etc.
Whats the difference between Html.Partial and Html.RenderPartial ?
The Partial helper renders a partial view into a string.
RenderPartial writes directly to the response output stream instead of returning a string.
Value Provider and Model Binder
ASP.NET 4.5 Web Forms support model binding. A part of the overall model binding features are Value Providers. A value provider grabs values from a request and binds those values with method parameters.
The framework contains a few built-in value providers named FormValueProvider, RouteDataValueProvider, QueryStringValueProvider and HttpFileCollectionValueProvider that fetch data from Request.Form, Request.QueryString, Request.Files and RouteData.Values.
NonActionAttribute
By default, the MVC framework treats all public methods of a controller class as action methods. If your controller class contains a public method and you do not want it to be an action method, you must mark that method with the NonActionAttribute attribute.
https://stackoverflow.com/
NonActionAttribute
By default, the MVC framework treats all public methods of a controller class as action methods. If your controller class contains a public method and you do not want it to be an action method, you must mark that method with the NonActionAttribute attribute.
https://stackoverflow.com/
ChildActionOnly Attribute In MVC
The action method which is decorated with the ChildActionOnly attribute is called a child action method.
Child action methods do not respond to URL requests. If an attempt is made, a runtime error is thrown stating that Child action is accessible only by a child request.
Child action methods can be invoked by making child request from a view using Action() and RenderAction() HTML helpers.
An action method doesn’t need to have [ChildActionOnly] attribute to be used as a child action but uses this attribute to prevent if you want to prevent the action method from being invoked as a result of a user request.
What is Repository Pattern?
The nice thing about the repository pattern is that it makes it easier to unit test your app and easier to maintain your application.
it makes it easy to change data access layer. If you want to switch from a local DB to a cloud based db, it's easy with the repository pattern.
to Read More Click on the below Link:
Unit of Work in the Repository Pattern
Unit of Work is referred to as a single transaction that involves multiple operations of insert/update/delete and so on kinds. To say it in simple words, it means that for a specific user action (say registration on a website), all the transactions like insert/update/delete and so on are done in one single transaction, rather then doing multiple database transactions. This means, one unit of work here involves insert/update/delete operations, all in one single transaction. https://www.c-sharpcorner.com
Anonymous Methods: – In simple words Anonymous Methods means method which are coded inline or methods without method name.
An anonymous method uses the keyword delegate, instead of method name.
An anonymous method uses the keyword delegate, instead of method name.
JSON(JavaScript Object Notation) - JSON is a lightweight, language independent data interchange format. Much like XML.
- JSON is lightweight text-data interchange format.
- JSON is language independent .
- JSON is "self-describing" and easy to understand.
- JSON is smaller than XML, and faster and easier to parse.
LINQ is a technique for querying data from any Datasource. data source could be the collections of objects, database or XML
files. We can easily retrieve data from any object that implements the
IEnumerable<T> interface.
Advantages: as Linq Queries is integrated with .net c# language , it enables
you to write code much faster then than if you were writing oldstyle queries. In some cases I have seen, by
using LINQ development time cut in half.
int[] nums = new int[] {0,1,2};
var res = from a in nums
where a < 3
orderby a
select a;
foreach(int i in res)
Console.WriteLine(i);
Dependency Injection basically allows us to create loosely coupled, reusable, and testable objects in your software designs by removing dependencies.
IoC (inversion of control) is a design pattern used to uncouple classes to avoid strong dependencies between them.
What are the different types of IOC (dependency injection) ?
There are four types of dependency injection:
- Constructor Injection): Dependencies are provided as constructor parameters.
- Getter-Setter Injection : Dependencies are assigned through properties (ex: setter methods).
- Interface Injection: Injection is done through an interface.
- Service Locater: What is the difference between loose coupling and tight coupling in object oriented paradigm?
In general, loose coupling is recommended because it's easier to test and maintain.
Tight coupling is when a group of classes are highly dependent on one another.
A loosely-coupled class can be consumed and tested independently of other (concrete) classes.
*******************************************************************************
The view engine is responsible for creating HTML from your views. Views are usually some kind of mixup of HTML and a programming language.
The Razor View Engine: It’s a type of View Engion that is introduced in MVC3 that offers some benefits that like:
1- Razor syntax is clean and concise, requiring a minimum number of code.
2- it's based on existing languages like C# and Visual Basic.
3- Razor views can be unit tested without requiring that you run the application or launch a web server.
Some new Razor features include the following:
- @model syntax for specifying the type being passed to the view.
- @* *@ comment syntax.
- The ability to specify defaults (such as layoutpage) once for an entire site.
- The Html.Raw method for displaying text without HTML-encoding it.
- Support for sharing code among multiple views (_viewstart.cshtml or _viewstart.vbhtml files)
JsonConvert.SerializeObject()
Serializes the specified object to a JSON string in c#.
Example:
Employee employee=new Employee
{
FirstName = "Suraj",
LastName = "Kumar"
};
string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(employee);
Console.WriteLine(jsonString);
For More information : Click here
JavaScriptSerializer
Class
Json.NET should be used
serialization and deserialization. Provides serialization and deserialization
functionality for AJAX-enabled applications.
Example: The below example provides a simple illustration of how to serialize and deserialize data objects. It requires a class names Employee which is shown below.
Employee employee=new Employee
{
FirstName = "Suraj",
LastName = "Kumar"
};
var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(employee);
var deserializedResult = javaScriptSerializer.Deserialize<Employee>(employeeDetail);
For More information : Click here
Why is JsonRequestBehavior needed in Jsonresult method?
By default, the ASP.NET MVC framework does not allow you to respond to an HTTP GET request with a JSON payload. If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method.
What is the difference between
$.ajax()
and $.get()
$.ajax()
Perform an asynchronous HTTP (Ajax) request.
$.ajax() is the most configurable one, where you get fine grained control over HTTP headers and such. You have to deal with the returned data yourself with a callback.
$.get()
Load data from the server using a HTTP GET request.
$.get() is just a shorthand for $.ajax(). Returns the data to a callback.
for more interview Questions follow the link -
http://www.codeproject.com/Articles/556995/Model-view-controller-MVC-Interview-questions-and
https://www.c-sharpcorner.com/UploadFile/8ef97c/most-asked-Asp-Net-mvc-interview-questions-and-answers/
Very knowledgeable post. I recommend this page for new person planning to learn MvC.
ReplyDeleteThanks Dear :)
Deletevery informative blog and useful article thank you for sharing with us , keep posting learn more Ruby on Rails Online Course Hyderabad
ReplyDelete