0% found this document useful (0 votes)
12 views

Lab Week 3

ASP.NET MVC is a web application framework that uses the model-view-controller pattern. It separates an application into three main components: the model, the view, and the controller. The framework provides features like routing, Razor views, model binding, validation, authentication and authorization.

Uploaded by

Suraj Thapa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Lab Week 3

ASP.NET MVC is a web application framework that uses the model-view-controller pattern. It separates an application into three main components: the model, the view, and the controller. The framework provides features like routing, Razor views, model binding, validation, authentication and authorization.

Uploaded by

Suraj Thapa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

ASP.

NET MVC
ASP.NET MVC is a web application development framework that is used to build dynamic and
scalable web applications. It is based on the Model-View-Controller (MVC) architectural pattern
and is developed by Microsoft.
The MVC pattern separates the application logic into three interconnected components:
 Model: Represents the application's data and the business rules that govern how the data
is accessed and manipulated
 View: Defines the presentation layer of the application, which includes the user interface
and the way the data is displayed to the user.
 Controller: Acts as an intermediary between the model and the view, processing user
input, updating the model, and rendering the view.
ASP.NET MVC is built on top of the ASP.NET framework and provides several features that
make web development easier and more efficient. These include:
1. Routing: Allows developers to define URL patterns for their applications, making it
easier to navigate between pages.
2. Razor View Engine: Provides a lightweight syntax for creating dynamic web pages.
3. Model Binding: Automatically maps HTTP request data to controller action parameters.
4. Validation: Provides a framework for validating user input and ensuring data integrity.
5. Authentication and Authorization: Allows developers to add security features to their
applications, such as user authentication and authorization.
Overall, ASP.NET MVC is a powerful web development framework that allows developers to
build robust and scalable web applications with ease.

 Action
In ASP.NET MVC, an action is a method on a controller that is responsible for
processing a user's request and generating a response. An action is invoked when a user
navigates to a URL that matches the routing pattern defined in the application's
RouteConfig file.
o Actions are responsible for performing the following tasks:
o Retrieve data from the database or other data sources
o Update data in the database or other data sources
o Create views that display data to the user
o Handle user input, such as form submissions
o Redirect users to other pages or actions
Practical 16
Objective:
 To implement simple MVC project.
Code
//HomeController.cs
using Microsoft.AspNetCore.Mvc;
using Practical_16.Models;
using System.Diagnostics;

namespace Practical_16.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)


{
_logger = logger;
}

public IActionResult Index()


{
return View();
}

public IActionResult Privacy()


{
return View();
}

public IActionResult Suraj()


{
return View();
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]


public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}

//Index.cshtml
@{
ViewData["Title"] = "Home Page";
}

<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

//Privacy.cshtml
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>

<p>Use this page to detail your site's privacy policy.</p>

//Suraj.cshtml

@{
ViewData["Title"] = "Suraj";
}

<h1>Suraj</h1>
<p>Welcome to the page of Suraj Thapa</p>
<p>Here new action as "Suraj" and view has been added.</p>

Output
Action “Home”

Action “Privacy”

Action and view “Suraj” has been added.


Action Result types in .NET MVC
In ASP.NET MVC, an action method returns an instance of the ActionResult class or one of its
derived classes, which determines the type of result that is returned to the client. Here are some
commonly used ActionResult types in ASP.NET MVC:
1. ViewResult - Returns a view that renders HTML content to the client. It takes a view
name and a model object as parameters, and returns an instance of the ViewResult class.
2. PartialViewResult - Returns a partial view that can be used to update part of a page
without refreshing the entire page. It takes a view name and a model object as
parameters, and returns an instance of the PartialViewResult class.
3. JsonResult - Returns JSON data that can be consumed by client-side scripts. It takes a
model object as a parameter, and returns an instance of the JsonResult class.
4. RedirectResult - Redirects the client to a different URL. It takes a URL string as a
parameter, and returns an instance of the RedirectResult class.
5. FileResult - Returns a file to the client. It takes a file path and a MIME type as
parameters, and returns an instance of the FileResult class.

Model Binding
Model binding is a feature in ASP.NET MVC that maps HTTP request data to action method
parameters or model properties. When a request is made to an action method, ASP.NET MVC
automatically maps the request data to the parameters of the method based on the parameter
names and types. Model binding simplifies the process of extracting data from the request and
eliminates the need for developers to write code to extract data from the request.
Model binding works by inspecting the request data and attempting to match it with the
parameters of the action method or properties of the model. If a match is found, the data is
mapped to the parameter or property. If a match is not found, the parameter or property is left
with its default value.
Practical 17
Objective:
 To add new controller in MVC project and return different action result.
Code
//BmcController.cs
using Microsoft.AspNetCore.Mvc;

namespace Practical_16.Controllers
{
public class BmcController : Controller
{
public IActionResult Bmc()
{
return View();
}
public IActionResult Contact()
{
return View();
}

public IActionResult Content()


{
return Content("This is a content return test by action");
}
public JsonResult json()
{
return Json(new {name ="Suraj", address="BMC"});
}
public IActionResult Partial()
{
return PartialView("Bmc");
}
}
}

//Bmc.cshtml
@{
ViewData["Title"] = "Bmc";
}
<h1>Bmc</h1>
<h2>Welcome to the page of Bhaktapur Multiple Campus</h2>

//Contact.cshtml
@{
ViewData["Title"] = "Contact";
}
<h1>Contact</h1>
<h2>For more details, contact: 01-6610200</h2>
Output

Output for action return type


Content type

Json type
Partial type

Now, making “StudentModel” inside Model folder.


The name should always end with Modelprefix.
Now,
//StudentModel.cs
namespace WebApplication2.Models
{
public class StudentModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string CollegeName { get; set; }
}
}
Now adding controller Student and views
//Studentcontroller.cs
using Microsoft.AspNetCore.Mvc;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
public class StudentController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult StudentView()
{
StudentModel suraj= new StudentModel();
suraj.FirstName = "Suraj";
suraj.LastName = "Thapa";
suraj.Age = 21;
suraj.Address = "Balkhu";
suraj.CollegeName = "BMC";
return View(suraj);
}
public IActionResult StudentDetail()
{
StudentModel nishant = new StudentModel();
nishant.FirstName = "Nishant";
nishant.LastName = "Kumpakha";
nishant.Age = 21;
nishant.Address = "BKT";
nishant.CollegeName = "BMC";

StudentModel santosh = new StudentModel();


santosh.FirstName = "Santosh";
santosh.LastName = "Kunwar";
santosh.Age = 21;
santosh.Address = "Gundu";
santosh.CollegeName = "BMC";

List<StudentModel> students = new List<StudentModel>();


students.Add(nishant);
students.Add(santosh);
return View(students);
}
}
}
Now adding view following is formed.
This is customized model.
//StudentView.ccshtml
@model StudentModel
@{
ViewData["Title"] = "StudentView";
}

<h1>StudentView</h1>
<label>First Name</label>
<label>@Model.FirstName</label><br>
<label>Last Name</label>
<label>@Model.LastName</label><br>
<label>Age</label>
<label>@Model.Age</label><br>
<label>Address</label>
<label>@Model.Address</label><br>
<label>Collegename</label>
<label>@Model.CollegeName</label><br>
Output:
For a single student

Here, list template is used.


//StudentDetail.cshtml
@model IEnumerable<WebApplication2.Models.StudentModel>

@{
ViewData["Title"] = "StudentDetail";
}

<h1>StudentDetail</h1>

<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.CollegeName)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.CollegeName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</tbody>
</table>

Output: Displaying list of students data

You might also like