Here we'll talk about ASP.NET MVC, can be build either thru .NET Framework or .NET Core
Project Structure:
0). MVC Versions & Features:
1) Define Default Routing in MVC?
- This is defined in App_Start/RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
2) Define Custom Routing in MVC to handle incoming requests that look like this: /Archive/12-25-2009
- This is defined in App_Start/RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Blog", // Route name
url: "Archive/{entryDate}", // URL with parameters
defaults: new { controller = "Archive", action = "Entry" } // Parameter defaults
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
public class ArchiveController : Controller
{
public string Entry(DateTime entryDate)
{
return "You requested the entry from " + entryDate.ToString();
}
}
3) Define Routing Constraints in MVC ?
- In above custom route, url ‘/Archive/apple’ will produce error - Because the Entry() action expects an DateTime parameter
- To avoid this make a constraint – when defining a route to restrict the URLs that match the route.
- This constraint causes the Archive route to not to match the URL - ‘/Archive/apple’ and so no error at runtime.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Blog", // Route name
url: "Archive/{entryDate}", // URL with parameters
defaults: new { controller = "Archive", action = "Entry" }, // Parameter defaults
new { entryDate = @"\d{2} - \d{2} - \d{4}" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
4). How to prevent a Public Action Method from Being Invoked
- Use [NonAction] attribute.
- Any attempt to invoke such controller action will result into an error message
namespace MvcApplication1.Controllers
{
public class BookController : Controller
{
[NonAction]
public ActionResult Index()
{
return View();
}
}
}
5). What are different Action Results ?
- A controller action returns something called an Action Result, in response to a browser request.
- ASP.NET MVC supports several types of action results including below (inherit from the base ActionResult class)
1. ViewResult – Represents HTML and markup.
2. EmptyResult – Represents no result.
3. RedirectResult – Represents a redirection to a new URL.
4. JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.
5. JavaScriptResult – Represents a JavaScript script.
6. ContentResult – Represents a text result.
7. FileContentResult – Represents a downloadable file (with the binary content).
8. FilePathResult – Represents a downloadable file (with a path).
9. FileStreamResult – Represents a downloadable file (with a file stream).
- In most cases, a controller action returns a ViewResult. When an action returns a ViewResult, HTML is returned to the browser.
- However the ViewResults is not returned directly. Instead, you call one of the following methods of the Controller base class to return the ViewResult.
1. View – Returns a ViewResult action result.
2. Redirect – Returns a RedirectResult action result.
3. RedirectToAction – Returns a RedirectToRouteResult action result.
4. RedirectToRoute – Returns a RedirectToRouteResult action result.
5. Json – Returns a JsonResult action result.
6. JavaScriptResult – Returns a JavaScriptResult.
7. Content – Returns a ContentResult action result.
8. File – Returns a FileContentResult, FilePathResult, or FileStreamResult depending on the parameters passed to the method.
6). What are HTML Helpers in MVC ?
- An HTML Helper is just a method that returns a string. The string can represent any type of content that you want.
- Below are few standard HTML Helpers (this is not a complete list):
- Html.ActionLink()
- Html.BeginForm()
- Html.CheckBox()
- Html.DropDownList()
- Html.EndForm()
- Html.Hidden()
- Html.ListBox()
- Html.Password()
- Html.RadioButton()
- Html.TextArea()
- Html.TextBox()
7). What are Filters in MVC ?
- The ASP.NET MVC framework supports four different types of filters:
- Base class for all action filters is the System.Web.Mvc.FilterAttribute class.
namespace MvcApplication1.ActionFilters
{
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Log("OnActionExecuting", filterContext.RouteData);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
Log("OnActionExecuted", filterContext.RouteData);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
Log("OnResultExecuting", filterContext.RouteData);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
Log("OnResultExecuted", filterContext.RouteData);
}
private void Log(string methodName, RouteData routeData)
{
var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
}
}
}
- Usage:
namespace MvcApplication1.Controllers
{
[LogActionFilter]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
}
}
8). What is Output Caching in MVC?
- Achieved thru OutputCache Action Filter
- Uses to caches the output of a controller action for a specified amount of time.
- Cache the content returned by any controller method so same content does not need to be generated each time the same controller method is invoked.
- Reduces server round trips, reduces database server round trips, reduces network traffic, etc.
9). What is MVC Application Life Cycle?
- MVC application life cycle is not different it has two main phases, first creating the request object and second sending our response to the browser.
- Creating the request object includes four basic steps:
10).Understanding the MVC Application Execution Process (C#)
- This is standard - Module Followed By Handler
11).What are different ways to store data like in Sessions
- ViewBag
- ViewData
- TempData
12).What is Validation Summary ? (https://www.aspsnippets.com/Articles/Display-Validation-Summary-in-ASPNet-MVC.aspx)
Hope this helps...
Arun Manglick
Project Structure:
0). MVC Versions & Features:
- MVC 1.0 | VS2008 |.Net 3.5 | 13-Mar-2009
- MVC architecture with webform engine
- Routing
- HTML Helpers
- Ajax Helpers
- Auto binding
- MVC 2.0 | VS 2008 |.Net 3.5/4.0 | 10-Mar-2010
- Area
- Asynchronous controller
- Html helper methods with lambda expression
- DataAnnotations attributes
- Client side validation
- Custom template
- Scaffolding
- Templated Helpers
- Html.ValidationSummary Helper Method
- DefaultValueAttribute in Action-Method Parameters
- Binding Binary Data with Model Binders
- Model-Validator Providers
- New RequireHttpsAttribute Action Filter
- Templated Helpers
- Display Model-Level Errors
- MVC 3.0 | VS 2010 | .Net 4.0 | 13-Jan-2011
- Unobtrusive javascript validation
- Razor view engine
- Global filters
- Remote validation
- Dependency resolver for IoC
- ViewBag
- HTML 5 enabled templates
- Model Validation Improvements
- MVC 4.0 | VS 2010 - 2012 | .NET 4.0/4.5 | 15-Aug-2012
- Mobile project template
- Bundling and minification
- Support for Windows Azure SDK
- ASP.NET Web API
- Enhanced support for asynchronous methods
- MVC 5.0 | VS 2013 |.NET 4.5 | 17-oct-2013
- Authentication filters
- Bootstrap support
- New scaffolding items
- ASP.Net Identity
- Attribute based routing
- Filter overrides
- MVC 5.2 | VS 2013 |.NET 4.5 | 28-Aug-2014
- Attribute based routing
- Bug fixes and minor features update
- MVC 6
- ASP.NET MVC and Web API has been merged in to one.
- Dependency injection is inbuilt and part of MVC.
- Side by side - Deploy the runtime and framework with your application
- Everything packaged with NuGet, Including the .NET runtime itself.
- New JSON based project structure.
- No need to recompile for every change. Just hit save and refresh the browser.
- Compilation done with the new Roslyn real-time compiler.
- vNext is Open Source via the .NET Foundation and is taking public contributions.
- vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.
1) Define Default Routing in MVC?
- This is defined in App_Start/RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
2) Define Custom Routing in MVC to handle incoming requests that look like this: /Archive/12-25-2009
- This is defined in App_Start/RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Blog", // Route name
url: "Archive/{entryDate}", // URL with parameters
defaults: new { controller = "Archive", action = "Entry" } // Parameter defaults
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
public class ArchiveController : Controller
{
public string Entry(DateTime entryDate)
{
return "You requested the entry from " + entryDate.ToString();
}
}
3) Define Routing Constraints in MVC ?
- In above custom route, url ‘/Archive/apple’ will produce error - Because the Entry() action expects an DateTime parameter
- To avoid this make a constraint – when defining a route to restrict the URLs that match the route.
- This constraint causes the Archive route to not to match the URL - ‘/Archive/apple’ and so no error at runtime.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Blog", // Route name
url: "Archive/{entryDate}", // URL with parameters
defaults: new { controller = "Archive", action = "Entry" }, // Parameter defaults
new { entryDate = @"\d{2} - \d{2} - \d{4}" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
4). How to prevent a Public Action Method from Being Invoked
- Use [NonAction] attribute.
- Any attempt to invoke such controller action will result into an error message
namespace MvcApplication1.Controllers
{
public class BookController : Controller
{
[NonAction]
public ActionResult Index()
{
return View();
}
}
}
5). What are different Action Results ?
- A controller action returns something called an Action Result, in response to a browser request.
- ASP.NET MVC supports several types of action results including below (inherit from the base ActionResult class)
1. ViewResult – Represents HTML and markup.
2. EmptyResult – Represents no result.
3. RedirectResult – Represents a redirection to a new URL.
4. JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX application.
5. JavaScriptResult – Represents a JavaScript script.
6. ContentResult – Represents a text result.
7. FileContentResult – Represents a downloadable file (with the binary content).
8. FilePathResult – Represents a downloadable file (with a path).
9. FileStreamResult – Represents a downloadable file (with a file stream).
- In most cases, a controller action returns a ViewResult. When an action returns a ViewResult, HTML is returned to the browser.
- However the ViewResults is not returned directly. Instead, you call one of the following methods of the Controller base class to return the ViewResult.
1. View – Returns a ViewResult action result.
2. Redirect – Returns a RedirectResult action result.
3. RedirectToAction – Returns a RedirectToRouteResult action result.
4. RedirectToRoute – Returns a RedirectToRouteResult action result.
5. Json – Returns a JsonResult action result.
6. JavaScriptResult – Returns a JavaScriptResult.
7. Content – Returns a ContentResult action result.
8. File – Returns a FileContentResult, FilePathResult, or FileStreamResult depending on the parameters passed to the method.
6). What are HTML Helpers in MVC ?
- An HTML Helper is just a method that returns a string. The string can represent any type of content that you want.
- Below are few standard HTML Helpers (this is not a complete list):
- Html.ActionLink()
- Html.BeginForm()
- Html.CheckBox()
- Html.DropDownList()
- Html.EndForm()
- Html.Hidden()
- Html.ListBox()
- Html.Password()
- Html.RadioButton()
- Html.TextArea()
- Html.TextBox()
7). What are Filters in MVC ?
- The ASP.NET MVC framework supports four different types of filters:
- Authorization filters -
- Implements IAuthorizationFilter attribute.
- Used to implement authentication and authorization for controller actions
- Action filters
- Implements IActionFilter attribute.
- Contain logic that is executed before and after a controller action executes.
- You can use an action filter, for instance, to modify the view data that a controller action returns.
- Few Action filters:
- OutputCache – This action filter caches the output of a controller action for a specified amount of time.
- HandleError – This action filter handles errors raised when a controller action executes.
- Authorize – This action filter enables you to restrict access to a particular user or role.
- Result filters
- Implements IResultFilter attribute.
- Contains 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
- Implements IExceptionFilter attribute
- Used to handle errors raised by either your controller actions or controller action results.
- You also can use exception filters to log errors.
- Base class for all action filters is the System.Web.Mvc.FilterAttribute class.
- To implement a particular type of filter, Then
- You need to create a class that inherits from the Base Filter class (e.g. ActionFilterAttribute) and
- Implements one or more of the IAuthorizationFilter, IActionFilter, IResultFilter, or ExceptionFilter interfaces.
namespace MvcApplication1.ActionFilters
{
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Log("OnActionExecuting", filterContext.RouteData);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
Log("OnActionExecuted", filterContext.RouteData);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
Log("OnResultExecuting", filterContext.RouteData);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
Log("OnResultExecuted", filterContext.RouteData);
}
private void Log(string methodName, RouteData routeData)
{
var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
}
}
}
- Usage:
namespace MvcApplication1.Controllers
{
[LogActionFilter]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
}
}
8). What is Output Caching in MVC?
- Achieved thru OutputCache Action Filter
- Uses to caches the output of a controller action for a specified amount of time.
- Cache the content returned by any controller method so same content does not need to be generated each time the same controller method is invoked.
- Reduces server round trips, reduces database server round trips, reduces network traffic, etc.
9). What is MVC Application Life Cycle?
- MVC application life cycle is not different it has two main phases, first creating the request object and second sending our response to the browser.
- Creating the request object includes four basic steps:
- Step 1: Fill route
- Step 2: Fetch route
- Step 3: Request context created
- Step 4: Controller instance created
10).Understanding the MVC Application Execution Process (C#)
- This is standard - Module Followed By Handler
- Requests first pass thru UrlRoutingModule object, which is an HTTP module.
- This module parses request and performs route selection. I.e Selects first Route Object that matches current request.
- (A route object is a class that implements RouteBase, and is typically an instance of the Route class.)
- From selected Route object, module obtains IRouteHandler object (MvcRouteHandler) that is associated with the Route object.
- The IRouteHandler instance creates an IHttpHandler object (MvcHandler) and passes it the IHttpContext object.
- This MvcHandler object then selects the controller that will ultimately handle the request.
11).What are different ways to store data like in Sessions
- ViewBag
- ViewData
- TempData
- TempData - https://www.codeproject.com/Articles/786603/Using-TempData-in-ASP-NET-MVC
- It's a dictionary object derived from TempDataDictionary.
- TempData stays for a subsequent HTTP Request as opposed to other options (ViewBag and ViewData) those stay only for current request.
- So, TempdData can be used to maintain data between controller actions as well as redirects.
- An important thing about TempData is that it stores contents in Session object.
- Diff With Session - TempData gets destroyed immediately after it’s used in subsequent HTTP request, so no explicit action required.
12).What is Validation Summary ? (https://www.aspsnippets.com/Articles/Display-Validation-Summary-in-ASPNet-MVC.aspx)
- Generates an unordered list (UL element) of validation messages that are in the Model State Dictionary object.
- Can be used to display all the error messages for all the fields.
- Also can also be used to display custom error messages - For this you need to add custom errors into the ModelState in the appropriate action method
- ModelState.AddModelError(string.Empty, "Student Name already exists.");
- https://www.tutorialsteacher.com/mvc/htmlhelper-validationsummary
Hope this helps...
Arun Manglick