===================MVC===============
Question: Mention what does Model-View-Controller represent in an MVC application?
Model- It represents the application data domain. In other words applications business logic is contained within the model and
is responsible for maintaining data
View- It represents the user interface, with which the end users communicates.
In short all the user interface logic is contained within the VIEW.
Controller- It is the controller that answers to user actions.
Based on the user actions, the respective controller responds within the model and choose a view to render that display
the user interface. The user input logic is contained with-in the controller
Note: In MVC " ActionFilters" help you to execute logic while MVC action is executed or its executing.
======Explain what are the steps for the execution of an MVC project?
Receive first request for the application
Performs routing
Creates MVC request handler
Create Controller
Execute Controller
Invoke action
Execute Result
========Explain what is routing? What are the three segments for routing is important?===
Routing helps you to decide a URL structure and map the URL with the Controller.
The three segments that are important for routing is
ControllerName
ActionMethodName
Parameter
= Mention what is the difference between Temp data, View, and View Bag?
Temp data: It helps to maintain data when you shift from one controller to other controller.
View data: It helps to maintain data when you move from controller to view
View Bag: It's a dynamic wrapper around view data
Note: Session can be maintained in MVC by three ways tempdata, viewdata, and viewbag.
=> What is Action Result:
Question: Mention what does Model-View-Controller represent in an MVC application?
Model- It represents the application data domain. In other words applications business logic is contained within the model and
is responsible for maintaining data
View- It represents the user interface, with which the end users communicates.
In short all the user interface logic is contained within the VIEW.
Controller- It is the controller that answers to user actions.
Based on the user actions, the respective controller responds within the model and choose a view to render that display
the user interface. The user input logic is contained with-in the controller
Note: In MVC " ActionFilters" help you to execute logic while MVC action is executed or its executing.
======Explain what are the steps for the execution of an MVC project?
Receive first request for the application
Performs routing
Creates MVC request handler
Create Controller
Execute Controller
Invoke action
Execute Result
========Explain what is routing? What are the three segments for routing is important?===
Routing helps you to decide a URL structure and map the URL with the Controller.
The three segments that are important for routing is
ControllerName
ActionMethodName
Parameter
= Mention what is the difference between Temp data, View, and View Bag?
Temp data: It helps to maintain data when you shift from one controller to other controller.
View data: It helps to maintain data when you move from controller to view
View Bag: It's a dynamic wrapper around view data
Note: Session can be maintained in MVC by three ways tempdata, viewdata, and viewbag.
=> What is Action Result:
Action Result is a result of action methods or return types of action methods. Action result is an abstract class. It is a base class for all type of action results.
1. The View() method doesn't make new requests, it just renders the view without changing URLs in the browser's address bar.
2. The RedirectToAction() method makes new requests and URL in the browser's address bar is updated with the generated URL by MVC.
3. The Redirect() method also makes new requests and URL in the browser's address bar is updated, but you have to specify the full URL to redirect
4. Between RedirectToAction() and Redirect() methods, best practice is to use RedirectToAction() for anything dealing with your application actions/controllers. If you use Redirect() and provide the URL, you'll need to modify those URLs manually when you change the route table.
5. RedirectToRoute() redirects to a specific route defined in the Route table.
What is syntax of declare Redirect To Action Result and Redirect Result
- public ActionResult Index()
- {
- return RedirectToAction("Login", "Account");
- }
Redirect Result:
- public RedirectResult Index()
- {
- return Redirect("Home/Contact");
- }
=====Mention what is the difference between "ActionResult" and "ViewResult" ?
"ActionResult" is an abstract class while "ViewResult" is derived from "AbstractResult" class.
"ActionResult" has a number of derived classes like "JsonResult", "FileStreamResult" and "ViewResult" .
"ActionResult" is best if you are deriving different types of view dynamically.
=====Explain how you can send the result back in JSON format in MVC?==========================
In order to send the result back in JSON format in MVC, you can use "JSONRESULT" class.
====== List out the types of result in MVC?===============
ViewResult
PartialViewResult
EmptyResult
RedirectResult
RedirectToRouteResult
JsonResult
JavaScriptResult
ContentResult
FileContentResult
FileStreamResult
FilePathResult
=====Mention the order of the filters that get executed, if the multiple filters are implemented?
The filter order would be like
Authorization filters
Action filters
Result filters
Exception filters
In the end "Exception Filters" are executed.
Multiple Models in Single View in MVC
I have two models, Teacher and Student, and I need to display a list of teachers and students within a single view. How can we do this?
1. 1. Using Dynamic Model
ExpandoObject (the System.Dynamic namespace) is a class that was added to the .Net Framework 4.0 that allows us to dynamically add and remove properties onto an object at runtime.
Using this ExpandoObject, we can create a new object and can add our list of teachers and students into it as a property.
We can pass this dynamically created object to the view and render list of the teacher and student.
Example:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to my demo!";
dynamic mymodel = new ExpandoObject();
mymodel.Teachers = GetTeachers();
mymodel.Students = GetStudents();
return View(mymodel);
}
}
2. Using View Model
3. Using ViewData
4. Using ViewBag
5. Using Tuple
6. Using Render Action Method
A Partial View defines or renders a partial view within a view.
We can render some part of a view by calling a controller action method using the Html.RenderAction method.
The RenderAction method is very useful when we want to display data in the partial view. The disadvantages of this method is that there are only multiple calls of the controller.
In the following example, I have created a view (named partialView.cshtml) and within this view I called the html.RenderAction method to render the teacher and student list.
Controller Code
public ActionResult PartialView()
{
ViewBag.Message = "Welcome to my demo!";
return View();
}
/// <summary>
/// Render Teacher List
/// </summary>
/// <returns></returns>
public PartialViewResult RenderTeacher()
{
return PartialView(GetTeachers());
}
/// <summary>
/// Render Student List
/// </summary>
/// <returns></returns>
public PartialViewResult RenderStudent()
{
return PartialView(GetStudents());
}
view code:===============
@{
ViewBag.Title = "PartialView";
<h2>@ViewBag.Message</h2>
<div>
@{
Html.RenderAction("RenderTeacher");
Html.RenderAction("RenderStudent");
}
</div>
================================ Filters==================================
In ASP.NET MVC, a user request is routed to the appropriate controller and action method.
However, there may be circumstances where you want to execute some logic before or after an action method executes.
ASP.NET MVC provides filters for this purpose.
ASP.NET MVC Filter is a custom class where you can write custom logic to execute before or after an action method executes.
Filters can be applied to an action method or controller in a declarative or programmatic way.
Declarative means by applying a filter attribute to an action method or controller class and programmatic means by implementing a corresponding interface.
MVC provides different types of filters.
The following table list filter types, built-in filters for the type and
interface which must be implemented to create a custom filter class.
Filter Type Description Built-in Filter Interface
Authorization filters: Performs authentication and authorizes before executing action method.
[Authorize], [RequireHttps] IAuthorizationFilter
Action filters: Performs some operation before and after an action method executes.IActionFilter
Result filters: Performs some operation before or after the execution of view result. [OutputCache] IResultFilter
Exception filters: Performs some operation if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline. [HandleError] IExceptionFilter.
Filters can be applied at three levels.
1. Global Level
You can apply filters at global level in the Application_Start event of Global.asax.cs file by using default FilterConfig.RegisterGlobalFilters() mehtod. Global filters will be applied to all the controller and action methods of an application.
The [HandleError] filter is applied globaly in MVC Application by default in every MVC application created using Visual Studio as shown below.
2. Controller level:
Filters can also be applied to the controller class.
So, filters will be applicable to all the action method of Controller class if it is applied to a controller class.
example:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
3. Action method level
You can apply filters to an individual action method also. So, filter will be applicable to that particular action method only.
Example:
public class HomeController : Controller
{
[HandleError]
public ActionResult Index()
{
return View();
}
}
Order of filter:
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters
Create Custom Filter:
You can create custom filter attributes by implementing an appropriate filter interface for which you want to create a custom filter and also derive a FilterAttribute class so that you can use that class as an attribute.
For example, implement IExceptionFilter and FilterAttribute class to create custom exception filter. In the same way implement an IAuthorizatinFilter interface and FilterAttribute class to create a custom authorization filter.
=View Bag ..... View Data..... Temp Data=
View BaG:
ViewBag transfers data from the controller to the view, ideally temporary data which in not included in a model.
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
You can assign any number of propertes and values to ViewBag
The ViewBag's life only lasts during the current http request. ViewBag values will be null if redirection occurs.
ViewBag is actually a wrapper around ViewData.
View Data:
ViewData transfers data from the Controller to View, not vice-versa.
ViewData is derived from ViewDataDictionary which is a dictionary type.
ViewData's life only lasts during current http request. ViewData values will be cleared if redirection occurs.
ViewData value must be type cast before use.
ViewBag internally inserts data into ViewData dictionary. So the key of ViewData and property of ViewBag must NOT match.
ViewData is similar to ViewBag. It is useful in transferring data from Controller to View.
ViewData is a dictionary which can contain key-value pairs where each key must be string.
Example:
ViewData["Name"]=Bill
Temp Data:
TempData is useful when you want to transfer non-sensitive data from one action method to another action method of the same or a different controller as well as redirects.
It is dictionary type which is derived from TempDataDictionary.
TempData can be used to store data between two consecutive requests. TempData values will be retained during redirection.
TemData is a TempDataDictionary type.
TempData internaly use Session to store the data. So think of it as a short lived session.
TempData value must be type cast before use. Check for null values to avoid runtime error.
TempData can be used to store only one time messages like error messages, validation messages.
Call TempData.Keep() to keep all the values of TempData in a third request.
=======================Validation===========================
ASP.NET MVC uses DataAnnotations attributes for validation.
DataAnnotations attributes can be applied to the properties of the model class to indicate the kind of value the property will hold.
The following validation attributes available by default.
Required
StringLength
Range
RegularExpression
CreditCard
CustomValidation
EmailAddress
FileExtension
MaxLength
MinLength
Phone
Use ValidationSummary to display all the error messages in the view.
Use ValidationMessageFor or ValidationMessage helper method to display field level error messages in the view.
Check whether the model is valid before updating in the action method using ModelState.IsValid.
Enable client side validation to display error messages without postback effect in the browser.
========================Bundling=========================
Bundling: Bundling allow us to load the bunch of static files from the server into one http request.
Bundle Types:
MVC 5 includes following bundle classes in System.web.Optimization namespace:
ScriptBundle: ScriptBundle is responsible for JavaScript minification of single or multiple script files.
StyleBundle: StyleBundle is responsible for CSS minification of single or multiple style sheet files.
DynamicFolderBundle: Represents a Bundle object that ASP.NET creates from a folder that contains files of the same type.
Can you explain the page life cycle of MVC?
→App initialization
→Routing
→Instantiate and execute controller
→Locate and invoke controller action
→Instantiate and render view.
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.
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()
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
}
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();
}
https://medium.com/dot-net-tutorial/top-50-asp-net-mvc-interview-questions-with-answers-1fd9b1638c61