ASP.NET Core MVC Guide

ASP.NET Core MVC Guide

Complete overview of Models, Controllers, Views, AJAX calls and request flow.

Component Description
Model Holds data and validation rules. Example: StudentModel.cs
Controller Handles requests from the browser and returns Views or JSON responses.
View Displays data and user interface to the browser.
GET Action
[HttpGet("StudentEntry")]
public IActionResult StudentEntry()
{
    return View(new StudentModel());
}
Loads the Student Entry page.
POST Action
[HttpPost("Save")]
public IActionResult Save(StudentModel student)
{
    return Json(new
    {
        success = true
    });
}
Receives form data and processes save logic.
Validation
if (!ModelState.IsValid)
{
    return Json(new
    {
        success = false
    });
}
Validates all DataAnnotation attributes in the model.
AJAX Call
$.ajax({
    url:'/Student/Save',
    type:'POST',
    data:$("#frmStudent").serialize()
});
Submits form data without refreshing the page.
JSON Response
return Json(new
{
    success = true,
    message = "Saved"
});
Returns data back to JavaScript.

StudentModel Example

public class StudentModel
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Range(1,150)]
    public int Age { get; set; }

    public DateTime DOB { get; set; }

    public string Gender { get; set; }

    [EmailAddress]
    public string Email { get; set; }
}

MVC Request Flow

Step 1: User Opens StudentEntry Page

Step 2: Controller Returns View

Step 3: User Enters Data

Step 4: AJAX Calls Save Action

Step 5: Controller Receives StudentModel

Step 6: ModelState Validates Data

Step 7: Save Data To Database

Step 8: Return JSON Response

Step 9: SweetAlert Displays Result

MVC Folder Structure

Controllers
 └─ StudentController.cs

Models
 └─ StudentModel.cs

Views
 └─ Student
     └─ StudentEntry.cshtml

Best Practice: Keep business logic inside Services or Repository classes and use Controllers only for handling requests and responses.