ASP.NET MVC
ASP.NET MVC
3. Razor View: It is a special file with HTML and C# code in the same file. It has
an extension of .cshtml . If we have a path with the name Index inside the
Controller with the name Home . ASP.NET will then go into the Views > Home >
Index.cshtml to resolve the View.
public HomeController() {
db = new DataDB();
}
@model IEnumerable<Solution.DataProject.Models.DataType>
<div>
There are @Model.Count() restaurants in the DB.
</div>
.dll files: They’re files in the Microsoft Intermediate Language (MSIL) format.
Visual Studio takes the source code of the project, and compiles the C# and
the Scripts and the Configuration files to MSIL. The .dll is a common
executable file in the Windows environment.
IIS Server: Internet Information Services (IIS), is a Web Server for the Windows
environment. It can be used to host any web content on Windows. Visual
Studio, by default, uses a lightweight version of this, called IIS Express, to host
the code we run using the IDE.
.NET Configurations
Global.asax
Global.asax.cs
namespace NameOfProject.Web {
public class MvcApplication : System.Web.HttpApplication {
protected void Application_Start() {
// Startup Code for the Application
}
}
}
The above 2 files are auto generated. They’re responsible for the startup of the
app.
BundleConfig.cs
It has the support for bundling the CSS and JS files together, and minifying it.
RouteConfig.cs
It’s used to map the Routes for the application.
We can ignore as well as map specific routes from controllers.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
);
/**
* So, a url hit to '/home/contact/' will try to invoke
* the Contact method in HomeController.cs
Web.config
It’s an XML file, used for configuration. Most of its logic consists of “Bind
directives”. It binds the Web Server to the appropriate versions of the Assembly
Files. Most of these are irrelevant to the developer.
There is, however, a specific section in the config, called <appSettings> which is
used to define some Settings for the application. The defaults are used for
framework specific configurations. But we can add our own custom settings to it
and use those in our application.
Controllers in .NET
They are the same as Spring Controllers
They don’t need special strings to point to path, they are configured as shown
in Route.config .
There also exist a special type of controllers, called API Controllers in the
System. They cannot have special named methods. They will implement
methods by the name of Get(), Post(), Put(), Delete() et cetera.
Models in .NET
They are, for the most part, exactly like Models we are used to.
The annotations for [Required], [MaxLength] , et cetera are all provided by .NET
out of the box.
It works using the DbContext files. Our database must extend this class.
The DbContext file can then be used to describe our table structures.
ViewBag Property: It’s a dynamic object property that is present for, and
accessibly from every page. It can be used to store View specific
configurations or values. Example – The page title can be stored in the
ViewBag, and the ViewBag can then be accessed from Layout to dynamically
set the title for a View.
Sections in Views: They can be used to render more elements in the Layout
View. We can have a call to sections inside our Layout View using the
directive. The section can be
@RenderSection("nameOfSection", required: boolean)
defined in any of the subsequent views using the @section nameOfSection { ... }
directive.
Partial Views: This can be used to plug in the small reusable chunks of HTML
into our views. The syntax for calling a partial view inside a full view is
@Html.Partial("_nameOfView", modelElement) .
TempData: Used to send temporary data over via requests. Possible use case
– Can be used to show a Confirmation Message on a Redirect.
namespace Conference.Portal {
public class MyPortalController : Controller {
[HttpPost]
[ValidateAntiForgeryToken] // Used to prevent CSRF at
public ActionResult BookHotel(HotelOrder hotelOrder)
hotelService.bookHotel(hotelOrder);
The TempDate["Message"] can then be accessed inside the Layout or the View.
Front-End frameworks
: It is used to render Script bundles for client side libraries.
RenderScripts()
Application End
namespace ProjectName {
public class MvcApplication : HttpApplication {
public static void Register() {
HttpApplication.RegisterModule(typeof(LogModule)); /
}
Lifecycle of a Request
namespace MvcApplication {
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes
routes.Add(new Route("home/about", new SampleRouteHa
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home", action = "Index", id =
}
HttpModules
Classes that implement the IHttpModule interface and are designed to respond to
Lifecycle Events.
We can accomplish the same functionality from our Global.asax file as well.
But breaking it out into a Module makes the Project cleaner, and our code
becomes reusable.
Action Invoker
Model Binding
namespace MvcApplication.Filters {
public class WorkflowFilter : FilterAttribute, IActionFilter
private int _highestCompletedStage;
public int MinRequiredStage { get; set; };
public int CurrentStage { get; set; };
if (null != sessionId) {
Guid tracker;
if (Guid.TryParse(sessionId.ToString(), out trac
if (
filterContext.HttpContext.Request.Reques
&& CurrentStage >= _highestCompletedStag
) {
var applicant = _context.Applications.Fi
x => ApplicantTracker == tracker
);
applicant.WorkflowStage = CurrentStage;
_context.SaveChanges();
}
}
}
}
if (null != applicantId) {
Guid tracker;
if (Guid.TryParse(applicationId.ToString(), out
var _context = DependencyResolver().Current
_highestCompletedStage = _context.Applicants
x => ApplicantTracker == tracker
).WorkflowStage;
namespace MvcApplication.Controllers {
[WorflowFilter(
MinRequiredStage = (int) WorkflowValues.bin,
CurrentStage = (int) WorkflowValues.ApplicantInfo
)]
public class ApplicantController : Controller {
}
}
serializer.Serialize(response.Output, data);
}
}
}
namespace MvcApplication.CustomResults {
public class CsvResult : FileResult {
private IEnumerable _data;
namespace MvcApplication.Controller {
public class FilesController : Controller {
// The Controller Initialization Logic is irrelevant