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

dotnet-lab3-MVC

The document is a lab assignment on ASP.NET MVC, detailing its architecture and features such as routing, Razor view engine, and action filters. It explains the roles of Model, View, and Controller, and provides examples of action methods and return types in a .NET MVC application. Additionally, it covers model binding and includes code snippets for controllers and views related to a student model, demonstrating how to handle user input and display data in a web application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

dotnet-lab3-MVC

The document is a lab assignment on ASP.NET MVC, detailing its architecture and features such as routing, Razor view engine, and action filters. It explains the roles of Model, View, and Controller, and provides examples of action methods and return types in a .NET MVC application. Additionally, it covers model binding and includes code snippets for controllers and views related to a student model, demonstrating how to handle user input and display data in a web application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Bhaktapur Multiple Campus

Dudhpati-7, Bhaktapur, Nepal

Lab Assignment-3
Net Centric Computing (CSC 367)

Prepared By:
Suman Khadka
B.Sc. CSIT 076 Batch, 6th Semester
Roll no: 54 (section-B)

Submitted To:
Ramesh Kharbuja
Lecturer, Net Centric Computing
CSIT Department
ASP.NET MVC
ASP.NET MVC is a web application framework developed by Microsoft that follows the Model-
View-Controller (MVC) architectural pattern. It is a part of the ASP.NET framework and is used
for building scalable and maintainable web applications.
In the MVC pattern, the model represents the data and business logic, the view represents the
user interface, and the controller manages the communication between the model and the view.
ASP.NET MVC follows this pattern and provides developers with tools and features to build
web applications in a modular and maintainable way.
Some of the key features of ASP.NET MVC include:
1. Routing: It allows developers to define URL patterns for the application's pages and
actions.
2. Razor View Engine: A view engine that enables the creation of dynamic and reusable
views with HTML markup and C# code.
3. Action Filters: Enables developers to apply pre- or post-processing logic to controller
actions.
4. Dependency Injection: It allows for the easy integration of third-party libraries and
frameworks.
5. Testing: ASP.NET MVC provides built-in support for unit testing and integration testing.

In MVC, there are three main parts: the Model, the View, and the Controller. Here's what each
part does:
• Model: This is where the data and business logic of the application are stored. Think of it as
the "brain" of the application. It's responsible for managing and processing data.
• View: This is what the user sees on their screen. It's responsible for displaying the data from
the Model in a way that makes sense to the user.
• Controller: This is what ties the Model and the View together. It receives input from the
user, uses the Model to process that input, and then sends the results to the View to be
displayed.
➢ Action:
an Action in .NET MVC is a method defined in a Controller class that handles a specific
HTTP request from the user and returns an appropriate response. The Action is
responsible for processing the user's input, manipulating the data if necessary, and
selecting an appropriate View to be displayed to the user. Actions are an essential part of
the MVC architecture in .NET, and they allow developers to build dynamic, responsive
web applications.
Example:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to my website!";
return View();
}
}

In this example, we have a Controller called HomeController with an Action method


called Index. The Index Action is responsible for handling requests to the home page of
our website.
Inside the Index method, we're setting a message to be displayed on the home page using
the ViewBag property. Then, we're returning a View to be displayed to the user.
When a user navigates to the home page of our website, the ASP.NET MVC framework
uses routing to determine that the HomeController and Index method should handle the
request. The Index method executes, sets the message to be displayed, and returns the
corresponding View to the user's browser. The View is then rendered on the screen, and
the user sees the message "Welcome to my website!".

In .NET, the Model is typically implemented using classes that define the structure of the data
and any business rules that apply to that data. The View is typically implemented using a
templating language called Razor, which allows developers to mix HTML and C# code to
dynamically generate web pages. The Controller is implemented using C# classes that handle
incoming HTTP requests, manipulate the Model as necessary, and select the appropriate View to
display the response.
The ASP.NET MVC framework provides a set of tools and features to help developers build web
applications using the MVC pattern. This includes a routing engine that allows developers to
map URLs to specific Controller actions, and a powerful templating engine (Razor) that makes it
easy to create dynamic Views.
Overall, MVC in .NET is a way to organize the code of a web application into separate parts,
each with its own responsibility. This can make it easier to build and maintain large web
applications over time.
Program
//HomeController.cs
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using webMVC.Models;

namespace webMVC.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 Suman()
{
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>

//Suman.cshtml
@{
ViewData["Title"] = "Suman";
}

<h1>Suman Khadka</h1>
<p>Welcome to the page, Suman.</p>
<p>New action Suman and view is added.</p>

Output
Simple MVC project with the default templates.
Action “Home”
Action “Privacy”

Now Action and view “Suman” is added.


Action Result types in .NET MVC
In a .NET MVC application, an Action method in a Controller class is responsible for handling a
specific HTTP request from the user and returning an appropriate response. The response can
take many different forms, depending on what we want to do with the data.
There are several types of Action result types in .NET MVC, but here are some of the most
common ones:
1. ViewResult ( View() ): This result type is used to return a View to the user. The View is
typically an HTML page that is generated dynamically based on the data passed to it
from the Action method.
2. PartialViewResult ( PartialView() ): This result type is similar to a ViewResult, but it's
used to return a partial View that can be included inside another View. Partial Views are
useful for reusing code and keeping your Views modular.
3. JsonResult ( Json() ): This result type is used to return JSON data to the user. JSON is a
lightweight data format that's commonly used in web applications for exchanging data
between the client and server.
4. ContentResult ( Content() ): This result type is used to return a string of content directly
to the user's browser. This is useful for returning simple responses, such as error
messages or status codes.
5. RedirectResult ( Redirect() ): This result type is used to redirect the user to another
URL. This can be useful for handling authentication or authorization, or for redirecting
the user to a different page after they've completed an action.
6. FileResult ( File() ): This result type is used to return a file to the user. The file can be
any type of content, such as an image, PDF, or CSV file.
Model Binding
Model Binding is a feature of ASP.NET MVC that helps simplify the process of mapping HTTP
request data to the parameters of an Action method. In other words, when a user submits a form
or makes a request to an MVC controller, Model Binding automatically maps the data in the
request to the corresponding properties of a Model class.
For example, let's say we have a Model class called User with the properties FirstName and
LastName. When a user submits a form with fields for FirstName and LastName, Model
Binding will automatically create a new instance of the User class, set the FirstName and
LastName properties to the values from the form, and pass the User instance as a parameter to
the Action method.
This makes it much easier to handle user input in an MVC application, because we don't have to
manually parse the request data and map it to our Model classes. Instead, we can rely on Model
Binding to handle this process for us.
Model Binding is a powerful feature of ASP.NET MVC, and it's used extensively throughout
MVC applications to handle user input and generate responses based on that input. By
simplifying the process of mapping HTTP request data to our Model classes, Model Binding
helps make MVC applications more robust, efficient, and maintainable.

Adding new controller “BMC” in controller folder with several actions, views.
Styling is done in style.css which is included inside wwwroot because it is static.
Various return types are illustrated with the help of actions.

//BmcController.cs
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using webMVC.Models;

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

public IActionResult Content()


{
return Content("This is a content return test by action.");
}

public ContentResult Contents()


{
return Content("This is a content return test by ContentResult.");
}
public JsonResult json()
{
return Json(new {name = "suman", college = "BMC"});
}
public IActionResult Partial()
{
return PartialView("Bmc"); // layout is discarded
}
public IActionResult Download()
{
return File("myfiles/hello.txt", "text/plain", "myfile.txt");
}
}
}
//Bmc.cshtml
@{
ViewData["Title"] = "Bmc";
}

<h1>Bmc</h1>
<h2>Welcome to the Bhaktapur Multiple Campus homepage</h2>

//Contact.cshtml
@{
ViewData["Title"] = "Contact";
}

<h1>Contact</h1>
<p>Contact number: 01-6610200</p>

Output
Adding BmcController to Controllers and adding two actions Bmc() and Contact()
Outputs for Actions return types:
Content type

Json type
Partial type

File type

Now, makind “StudentModel” inside Model folder.


The name should always end with Modelprefix.
Now,
//StudentModel.cs
namespace webMVC.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 webMVC.Models;

namespace webMVC.Controllers
{
public class StudentController : Controller
{
public IActionResult Index()
{
return View();
}
public ActionResult StudentView()
{
StudentModel suman = new StudentModel();
suman.FirstName = "Suman";
suman.LastName = "Khadka";
suman.Age = 20;
suman.Address = "Kadaghari";
suman.CollegeName= "BMC";
return View(suman);
}

public ActionResult StudentsView()


{
StudentModel suman = new StudentModel();
suman.FirstName = "Suman";
suman.LastName = "Khadka";
suman.Age = 20;
suman.Address = "Kadaghari";
suman.CollegeName = "BMC";

StudentModel saini = new StudentModel();


saini.FirstName = "Saini";
saini.LastName = "Thapa Magar";
saini.Age = 21;
saini.Address = "Suryabinayak";
saini.CollegeName = "BMC";

StudentModel raj = new StudentModel();


raj.FirstName = "Raj";
raj.LastName = "Prajapati";
raj.Age = 24;
raj.Address = "Sano Thimi";
raj.CollegeName = "BMC";

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


Students.Add(suman);
Students.Add(saini);
Students.Add(raj);

return View(Students);
}
}
}
Now, adding view following is formed.
This is customized model.
//StudentView.cshtml
@model StudentModel

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

<h1>StudentView</h1>

<div>
<h4>StudentModel</h4>
<hr/>
</div>

<div>
<label>Name: </label>
<label>@Model.FirstName</label>
<label>@Model.LastName</label><br />
<label>Age: </label>
<label>@Model.Age</label><br />
<label>Address</label>
<label>@Model.Address</label><br />
<label>College Name: </label>
<label>@Model.CollegeName</label><br />

</div>

Output: for a single student


Here, List template is used.
//StudentsView.cshtml
@model IEnumerable<webMVC.Models.StudentModel>

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

<h1>StudentsView</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