MVC
An architectural pattern which separates the representation and user interaction :
View - Look and Feel
Model - Object, provide data to view
Controller - Take end user request and loading the appropriate Model and View.
It more suitable to WEB, Windows App user MVP.
|
ASP.NET Web Forms
|
ASP.NET MVC
|
development model
|
Form follow a traditional event driven
|
Is a lightweight and follow MVC (Model, View Controller) pattern
|
HTML
|
Server controls
|
HTML Helpers
|
Support view state
|
Yes
|
No
|
URL
|
File-based URLs (must have physical file name)
|
Route-based URL (based on controller not on physical file)
|
Syntax
|
Follow Web Forms Syntax
|
Follow customizable syntax (Razor as default)
|
Coupling
|
ASPX and ASPX.CS are tightly coupled
|
Views and logic are kept separately
|
Consistent Look
|
Master Pages
|
Layout
|
Page Reuse
|
User Controls
|
Partial Views
|
Open Source
|
No
|
Yes
|
Advantage of MVC
- Separate code behind to a separate class file, so we can reuse the code.
- Automated UI testing, it give us to wrote unit test and automate manual testing.
MVC Life Cycle
Creating the request object: -The request object creation has 4 steps:
Step 1 Fill route: MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if is the
first request, it will
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.
______________________________________________________________________________
TestController is the class name.
Test is the controller name.
In URL, you should type
Test only.
______________________________________________________________________________
Action method is a public method inside
controller which accepts user’s
request and returns
response.
public method in controller will automatically become action method. Non public method cannot invoked from the web.
Public method but not action method
[NonAction]
public string SimpleMethod()
{
return "Hi, I am not action method";
}
______________________________________________________________________________
HTML Helpers
Help you to render HTML controls in the view.
Html.TextBox("CustomerCode")
Html.TextBoxFor(m => m.CustomerCode) //using property name from object m.
ActionLink method can
navigate from one view to another using a hyperlink. E.g. below is navigate to "Home" controller and invoke "GotoHome" method.
<%= Html.ActionLink("Home","Gotohome") %>
______________________________________________________________________________
“input type=submit” request to the server .
“input type=button” perform some custom client side actions.
______________________________________________________________________________
We can restrict the MVC action with the
HttpGet or
HttpPost attribute. E.g. the DisplayCustomer action can only be invoked by HttpGet. If we try to make HTTP POST on DisplayCustomer, it will throw an error.
[HttpGet]
public ViewResult DisplayCustomer(int id)
{
Customer objCustomer = Customers[id];
return View("DisplayCustomer",objCustomer);
}
______________________________________________________________________________
Partial Views
Is a reusable view (like a user control) which can be embedded inside other views.
E.g. all your pages have a standard structure with left menu and header. So you can create partial views for each of these items and then you call that partial view in the main view.
<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>
______________________________________________________________________________
ASPX. Razor was introduced in MVC 3. It’s a clean and lightweight view engine. Syntaxes are easy as compared to ASPX.
ASPX
<%=DateTime.Now%>
Razor
@DateTime.Now
______________________________________________________________________________
ActionResult
- is an abstract class
- It has few derived classes like ViewResult, JsonResult, FileStreamResult, and so on.
- Can be used to exploit polymorphism and dynamism, for returning different types of views dynamically. Depending on the flag (IsHtmlView) it will either return a ViewResult or JsonResult.
public ActionResult DynamicView()
{
if (IsHtmlView)
return View(); else
return Json(); }
ViewResult - Renders a specified view to the response stream.
JsonResult - Serializes a given ViewData object to JSON format.
______________________________________________________________________________
ActionFilters help you to perform logic while an MVC action is executing or after an MVC action has executed.
Action filters are useful in the following scenarios:
- Implement post-processing logic before the action happens.
- Cancel a current execution.
- Inspect the returned value.
- Provide extra data to the action.
Types of the action filters (execute by sequence)
- Authorization filters
- Action filters
- Result filters
- Exception filters
You can create action filters by two ways:
1) Inline Action Filter
Need to implement the
IActionFilter interface.
The
IActionFilter interface has two methods:
OnActionExecuted and
OnActionExecuting. We can implement pre-processing logic or cancellation logic in these methods.
public class Default1Controller : Controller , IActionFilter
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
Trace.WriteLine("Action is executing");
}
}
2) Action Filter Attribute
The problem with the inline action attribute is that it cannot be reused across controllers.
So we can use Action Filter Attribute. We need to inherit from ActionFilterAttribute and implement the IActionFilter interface.
public class MyActionAttribute : ActionFilterAttribute , IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
Trace.WriteLine("Action executing");
}
}
The controllers on which we want the action attribute to execute.
[MyActionAttribute]
public class Default1Controller : Controller
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
}
______________________________________________________________________________
we can use
Request.HttpMethod to detect POST and GET action.
public ActionResult SomeAction()
{
if (Request.HttpMethod == "POST")
{
return View("SomePage");
}
else
{
return View("SomeOtherPage");
}
}
______________________________________________________________________________
Model is Business specific data. It will be created based on Business and Database structure.
ViewModel is View specific data. It will be created based on the View.
When use ViewModel ? E.g. DB Store FirstName and LastName, they are model. ViewModel = EmployeeName = FirstName and + LastName
Every view should have its own ViewModel although it's same as model. good for update in future.
______________________________________________________________________________
Bundling help combines multiple JavaScript and CSS files into a single entity thus minimizing multiple requests into a single request to increase performance.
Open BundleConfig.cs from the App_Start folder.
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js")); //All JS file
BundleTable.EnableOptimizations = true;
}
}
Execute at ASPX or Razor view.
<%= Scripts.Render("~/Scripts/MyScripts") %>
Minification is to reduce Script and CSS files size by removing blank spaces, comments and etc. Minification is implemented by itself when you implement bundling.
______________________________________________________________________________
Right clicking +
Area will group the controller classes.
______________________________________________________________________________
We can bind 2 models with a single view, but not from UI (because UI only can select 1)
so you do in the code manually.
public class CustOrderVM
{
public Customer cust = new Customer();
public Order Ord = new Order();
}
<%= model.cust.Name %>
<%= model.Ord.Number %>
______________________________________________________________________________
Check user agent and point to which view.
______________________________________________________________________________
In the controller, to
handle the
exception by override the “
OnException” event and set the “Result” to the view name which you want to invoke when the error occurs.
public class HomeController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
Exception ex = filterContext.Exception;
filterContext.ExceptionHandled = true;
var model = new HandleErrorInfo(filterContext.Exception, "Controller","Action");
filterContext.Result = new ViewResult()
{
ViewName = "Error",
ViewData = new ViewDataDictionary(model)
};
}
}
@Model.Exception;
______________________________________________________________________________
You can handle multiple submit button in an MVC view.
This is wrong, you press any of button also call "Action1" only.
<form action="Action1" method=post>
<input type=”submit” name=”Submit1”/>
<input type=”submit” name=”Submit2”>
</form>
1) HTML way : 2 Form and 2 Action
<form action="Action1" method=post>
<input type=”submit” name=”Submit1”/>
</form>
2) AJAX way : 2 Function and 2 Action
Create 2 functions "Fun1" and "Fun2", call using JQUERY
<Script language="javascript">
function Fun1()
{
$.post(“/Action1”,null,CallBack1);
}
function Fun2()
{
$.post(“/Action2”,null,CallBack2);
}
</Script>
3) 1 Form 1 Action
<input type="submit" name="BtnSubmit” value="Save Employee" />
<input type="button" name="BtnReset" value="Reset" onclick="ResetForm();" />
<input type="submit" name="BtnSubmit" value="Cancel" />
public ActionResult SaveEmployee(Employee e, string BtnSubmit)
{
switch (BtnSubmit)
{
case "Save Employee":
return Content(e.FirstName + "|" + e.LastName + "|" + e.Salary);
case "Cancel":
return RedirectToAction("Index");
}
return new EmptyResult();
}
// Not Related (Reset by client)
<script>
function ResetForm() {
document.getElementById( document.getElementById( document.getElementById( }
</script
https://www.codeproject.com/Articles/556995/ASP-NET-MVC-interview-questions-with-answers#Disclaimer