Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

ASP.NET MVC Architecture and Implementation Patterns

Tools Nov 7 26

Model-View-Controller Architecture Components

The Model-View-Controller pattern consists of three core components: Models (business logic), Views (presentation layer), and Controllers (request handling).

Controller Structure and Naming Convention

Controllers must follow the naming convention ending with "Controller". Each controller corresponds to a folder in the Views directory, where the "Controller" suffix is automatically removed from the folder name. Controller actions map to individual view pages.

URL routing follows this pattern:

/home/index 
/controller/action

The RouteConfig file in App_Start contains default route values. If no specific values are provided, these defaults are used automatically.

HTTP Method Restrictions

Actions can be restricted to specific HTTP methods using attributes:

[HttpGet] or [HttpPost]
public ActionResult Index()
{
    // Action implementation
}

Navigation and Page Display

Use RedirectToAction("action") to redirect to another action method.

Use View() to render a page.

For actions that don't require page rendering, change the return type to void:

public void Index()
{
    // Process without returning view
}

Data Transfer Between Controller and View

ViewBag serves as a dynamic container for passing data from controller to view. It accepts any data type:

ViewBag.Identifier = 1;
ViewBag.Username = "John Doe";
ViewBag.StudentObject = new Student();

In views, access ViewBag data using:

@{
    ViewBag.Username
}

or

@ViewBag.Username

To output HTML within C# code blocks:

@:This is HTML content

Alternative Data Containers

ViewData functions similarly to ViewBag but uses dictionary syntax:

ViewData["Username"] = "Jane Smith";

TempData operates like session storage but clears after first use, making it suitable for cross-page temporary data:

TempData["Username"] = "Bob Johnson";

Direct View Data Passing

Data can be passed directly through the View() method:

return View(1);
return View("Sample Text");
return View(new Student());

For strongly-typed views, add model reference:

@model MyApplication.Models.Student;

Model Binding

Controllers automatically bind request parameters to action method parameters:

public ActionResult Index(int id, string name)
{
    // Parameters auto-bound from request
}

When binding complex objects, property names match request parameters:

public ActionResult Index(Student student)
{
    // Properties matched by name
}

Custom Routing Configuration

Routers are registered via MapRoute() method. Custom routes must be defined before default routes:

routes.MapRoute(
    name: "custom_route",
    url: "articles/{id}",
    defaults: new { controller = "Articles", action = "Display", id = UrlParameter.Optional },
    constraints: new { id = @"\d+" } // Numeric validation
);

Attribute-Based Routing

Modern MVC versions support attribute routing:

[RoutePrefix("articles")]
public class ArticleController
{
    [Route("item/{id}")]
    public ActionResult GetItem(string id)    
    {
        return Content("Response content");
    }
}

Dynamic Link Generation

Generate URLs dynamically to avoid manual updates:

<a href="@Url.Action("action", "controller")">Link Text</a>

For specific route URLs:

<a href="@Url.RouteUrl("route_name", new { controller = "ctrl", action = "act", id = "param" })">Link Text</a>

Shared Views and Layouts

The Shared folder contains reusable components like master pages, partial views, and error pages. Files starting with underscore (_) cannot run independently.

Layout pages use @RenderBody() to indicate content placement:

return View("child_page", "master_layout");

Or specify layout in child view:

@{
    Layout = "~/Views/Shared/_Master.cshtml";
}

Layout sections allow targeted content placement:

RenderSection("section_name", required: true/false);

Child page section definition:

@section section_name {
    // Section content
}

Partial Views

Render partial views using:

@Html.Partial("partial_name", model_parameter);
or
@Html.RenderPartial("partial_name", model_parameter); // More efficient

Access parameters in partial views through @Model.

Configuration for Extension Support

To allow extensions in URLs, configure web.config:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

Action Result Types

All result types inherit from ActionResult:

  • View() returns ViewResult
  • RedirectToAction() returns RedirectToRouteResult
  • Json() returns JsonResult
  • File() returns FileContentResult

JSON results restrict GET requests by default:

return Json(new List<Student>()
{
    // Data collection
}, JsonRequestBehavior.DenyGet /* or AllowGet */);

AJAX Integration

Handle JSON responses with AJAX:

$.ajax({
    url: "endpoint_url",
    type: "get", // Request method
    dataType: "json" // Response format
}).done(function(data) {
    // Success handler
}).fail(function(error) {
    // Error handler
});

File Results

Return various file types using different File() parameter formats. Images and media files can be directly referenced in HTML tags:

<img src="/controller/action" />

Special Result Types

Other result options include:

  • HttpNotFoundResult() - 404 response
  • JavaScriptResult() - JavaScript output
  • EmptyResult() - Null response
  • HttpStatusCodeResult() - Custom status codes

Partial View Actions

Partial view actions provide processing capabilities:

@Html.Action("action_name");
or
@Html.RenderAction("action_name"); // More efficient

Form Creation

Create forms using:

@Html.BeginForm("action_name", "controller_name", FormMethod.Post, new { @class = "css-class", onsubmit = "validationFunction" })

JSON Handling

Create custom JSON result classes ihneriting from JsonResult:

return new JsonNetResult()
{
    Data = new List<Entity>()
    {
        new Entity(),
        new Entity()
    },
    JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

Template Processing

Simple template replacement:

var template = '<div>{{identifier}}</div>';
template.replace('{{identifier}}', actual_value);

Anchor Tag Generation

Generate links using:

@Html.ActionLink("link_text", "target_action");

@Html.ActionLink("sample_link", "destination");
// Generates: <a href="/index/destination">sample_link</a>

AJAX-Enhanced Links

AJAX-enabled anchor generation includes additional options:

@Ajax.ActionLink("text", "action", new AjaxOptions
{
    UpdateTargetId = 'container_id',
    Confirm = 'confirmation_message',
    LoadingElementId = 'loading_indicator_id',
    InsertionMode = InsertionMode.Replace
});

Requires jquery.unobtrusive-ajax.js for functionality.

Security Features

Prevent cross-site request forgery attacks using Html.AntiForgeryToken() combined with [ValidateAntiForgeryToken] attribute.

AJAX Forms

Generate AJAX forms with:

Ajax.BeginForm("action", "controller", new AjaxOptions
{
    OnSuccess = "successCallback",
    HttpMethod = "post"
}, new { id = "form-id" });

Strongly-Typed HTML Helpers

Generate form elements based on model properties:

  • Html.LabelFor() creates labels with optional display names
  • Html.EditorFor() generates input fields based on data annotations
  • Html.ValidationMessageFor() displays validation errors

Validation Attributes

Common validation patterns:

  • [Required(ErrorMessage = "message")] - Manadtory fields
  • [StringLength(100)] - Maximum length
  • [StringLength(100, MinimumLength=1)] - Length range
  • [RegularExpression(@"^pattern$")] - Pattern matching
  • [Range(1,100)] - Numeric range
  • [Remote("action", "controller")] - Server-side validation

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.