0% found this document useful (0 votes)
12 views31 pages

Backend

The document provides a comprehensive guide on creating an ASP.NET MVC application, including steps for setting up a welcome message, creating an employee model, demonstrating ViewData, ViewBag, TempData, and session variables, and implementing CRUD operations using Entity Framework. Each section outlines the necessary steps to create controllers, views, and models, along with code snippets and explanations. The document concludes with instructions for running the applications and viewing the results in a web browser.

Uploaded by

rwlrajat
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)
12 views31 pages

Backend

The document provides a comprehensive guide on creating an ASP.NET MVC application, including steps for setting up a welcome message, creating an employee model, demonstrating ViewData, ViewBag, TempData, and session variables, and implementing CRUD operations using Entity Framework. Each section outlines the necessary steps to create controllers, views, and models, along with code snippets and explanations. The document concludes with instructions for running the applications and viewing the results in a web browser.

Uploaded by

rwlrajat
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/ 31

Create and display welcome message using MVC and create custom

url by modifying in route.config file

📁 Step 1: Create a New ASP.NET MVC Project


1.​ Open Visual Studio.​

2.​ Click on Create a new project.​

3.​ Choose ASP.NET Web Application (.NET Framework).​

4.​ Click Next.​

5.​ Give it a name like WelcomeApp, then click Create.​

6.​ In the next window, choose MVC and click Create.​

✅ Yay! You just made a new website using MVC!

🧑‍🏫 Step 2: Create a Controller


1.​ In the Solution Explorer (right side), find the folder named Controllers.​

2.​ Right-click on Controllers ➜ click Add ➜ click Controller.​

3.​ Select MVC 5 Controller - Empty ➜ Click Add.​

4.​ Name it WelcomeController ➜ Click Add.​

✍️ Now replace the code inside it with this:


csharp
CopyEdit
using System.Web.Mvc;

namespace WelcomeApp.Controllers
{
public class WelcomeController : Controller
{
public ActionResult Greet()
{
ViewBag.Message = "Welcome to the MVC World!";
return View();
}
}
}

📌 ViewBag.Message is like writing a message on a paper to show in the next step.

👀 Step 3: Create a View (what you see on screen)


1.​ Right-click on the word Greet in Greet() method.​

2.​ Click on Add View....​

3.​ Name it Greet (same as the method) and click Add.​

Now change the code in the view to this:

html
CopyEdit
@{
ViewBag.Title = "Welcome Page";
}

<h1>@ViewBag.Message</h1>

🖥️ This tells the screen to show the message: "Welcome to the MVC World!"

🛣️ Step 4: Add a Custom URL in RouteConfig.cs


1.​ Go to App_Start ➜ Open RouteConfig.cs.​

2.​ Find this line:​

csharp
CopyEdit
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional
}
);

3.​ Replace it with this custom route:​

csharp
CopyEdit
routes.MapRoute(
name: "WelcomeRoute",
url: "greeting-page",
defaults: new { controller = "Welcome", action = "Greet" }
);

🚀 Now when someone types http://localhost:xxxx/greeting-page, they will see your welcome
message!

🎉 Final Step: Run Your App


●​ Press the green Start button (or press F5 on your keyboard).​

👉
●​ In the address bar, type:​
http://localhost:1234/greeting-page (your number might be different)​

✅ You should see: "Welcome to the MVC World!"

=========================================================
===========================
Create an employee model using strongly typed views

✅ STEP 1: Create a New Project


1.​ Open Visual Studio.​

2.​ Click "Create a new project".​

3.​ Choose "ASP.NET Web Application (.NET Framework)".​

4.​ Click Next.​

5.​ Name your project: EmployeeApp​

6.​ Click Create.​

7.​ Choose MVC and click Create.​

🎉 Yay! You created an MVC website project!

✅ STEP 2: Create a Model (Employee notebook 📓)


1.​ In Solution Explorer (right side), find and right-click the folder called Models.​

2.​ Click Add ➜ Class.​

3.​ Name the file: Employee.cs ➜ Click Add.​

4.​ Replace the code with this:​

csharp

CopyEdit

namespace EmployeeApp.Models

public class Employee

public int Id { get; set; }

public string Name { get; set; }

public string Department { get; set; }

public int Age { get; set; }


}

📓 This makes a blueprint for an employee with 4 things: Id, Name, Department, Age.

✅ STEP 3: Create a Controller (The Teacher 👩‍🏫)


1.​ Right-click the Controllers folder.​

2.​ Click Add ➜ Controller.​

3.​ Choose MVC 5 Controller - Empty ➜ Click Add.​

4.​ Name it: EmployeeController ➜ Click Add.​

Now put this code inside:

csharp

CopyEdit

using System.Web.Mvc;

using EmployeeApp.Models;

namespace EmployeeApp.Controllers

public class EmployeeController : Controller

public ActionResult Details()

Employee emp = new Employee

Id = 1,

Name = "Rajat",

Department = "IT",

Age = 25
};

return View(emp);

🧠 This creates an example employee and sends it to the screen.

✅ STEP 4: Create a View (Blackboard to show info 🎓)


1.​ Right-click on Details() method ➜ Click Add View.​

2.​ In the window:​

○​ Name: Details​

○​ Check “Create a strongly-typed view”​

○​ Choose EmployeeApp.Models.Employee as the model class​

○​ Click Add​

In the new file Details.cshtml, write this:

html

CopyEdit

@model EmployeeApp.Models.Employee

<h2>Employee Details</h2>

<p><strong>ID:</strong> @Model.Id</p>

<p><strong>Name:</strong> @Model.Name</p>

<p><strong>Department:</strong> @Model.Department</p>

<p><strong>Age:</strong> @Model.Age</p>
🧑‍🎓 @Model is like saying: “Show me the data from the Employee notebook!”

✅ STEP 5: Run Your Website! 🚀


1.​ Press the green Start button at the top (or press F5).​

2.​ In your browser, type this:​

arduino

CopyEdit

http://localhost:1234/Employee/Details

🎉 You’ll see:
makefile

CopyEdit

Employee Details

ID: 1

Name: Rajat

Department: IT

Age: 25

=========================================================
===========================
Write a program demonstrating ViewData,ViewBag, Temp data and session
variables

🏗️ Step-by-step Project Setup:


✅ Step 1: Create a New MVC Project
1.​ Open Visual Studio.​

2.​ Click Create a new project.​

3.​ Choose ASP.NET Web Application (.NET Framework) ➜ Click Next.​

4.​ Name it: DemoDataProject ➜ Click Create.​

5.​ Choose MVC and Click Create.​

🚀 You’ve made your new project!

✅ Step 2: Create a Controller (The Teacher)


Controller gives information to the View (like your teacher telling something to the board)

1.​ In Solution Explorer, right-click on the Controllers folder ➜ Click Add ➜ Controller.​

2.​ Choose MVC 5 Controller - Empty ➜ Click Add.​

3.​ Name it: HomeController ➜ Click Add.​

Now add this code inside HomeController.cs:

csharp
CopyEdit
using System.Web.Mvc;

namespace DemoDataProject.Controllers
{
public class HomeController : Controller
{
public ActionResult FirstPage()
{
ViewData["MyViewData"] = "Hello from ViewData!";
ViewBag.MyViewBag = "Hello from ViewBag!";
TempData["MyTempData"] = "Hello from TempData!";
Session["MySession"] = "Hello from Session!";

return RedirectToAction("SecondPage");
}

public ActionResult SecondPage()


{
return View();
}
}
}

💬 In simple words:
●​ We're putting messages in ViewData, ViewBag, TempData, and Session.​

●​ Then we are sending the user to another page (SecondPage) to show those messages!​

✅ Step 3: Create a View (The Blackboard 📓)


Now we create a page to show the messages

1.​ Right-click on the SecondPage() method ➜ Click Add View.​

2.​ Name it: SecondPage ➜ Click Add.​

Now paste this code in SecondPage.cshtml:

html
CopyEdit
<h2>Showing All Data</h2>

<p><strong>ViewData:</strong> @ViewData["MyViewData"]</p>
<p><strong>ViewBag:</strong> @ViewBag.MyViewBag</p>
<p><strong>TempData:</strong> @TempData["MyTempData"]</p>
<p><strong>Session:</strong> @Session["MySession"]</p>

✅ Step 4: Time to Run It! 🏃‍♂️💻


1.​ Click the green Start button (or press F5).​

2.​ In the browser, type this URL:​

arduino
CopyEdit
http://localhost:1234/Home/FirstPage
(Replace 1234 with your number)

🎉 You will see something like:


vbnet
CopyEdit
ViewData:
ViewBag:
TempData: Hello from TempData!
Session: Hello from Session!

💡 Why is ViewData and ViewBag empty?


Because they only work in the same request. When we did a Redirect, they got lost.

👨‍🔧 Want to fix that?


Go back to the controller and change this line:

csharp
CopyEdit
return RedirectToAction("SecondPage");

To this:

csharp
CopyEdit
return View("SecondPage");

Now run http://localhost:1234/Home/FirstPage again.

You will see:

vbnet
CopyEdit
ViewData: Hello from ViewData!
ViewBag: Hello from ViewBag!
TempData: Hello from TempData!
Session: Hello from Session!

====================================================================================
Write a program using Entity framework to provide facility to insert,
edit and delete

✅ Let's Start! Step-by-Step


We’ll use ASP.NET MVC + Entity Framework.

🔹 Step 1: Create a New Project


1.​ Open Visual Studio​

2.​ Click Create a new project​

3.​ Choose: ASP.NET Web Application (.NET Framework) ➜ Click Next​

4.​ Name it: StudentCRUDApp ➜ Click Create​

5.​ Choose: MVC ➜ Click Create​

🎉 Yay! Project created!

🔹 Step 2: Add the Entity Framework Robot


1.​ Click Tools ➜ NuGet Package Manager ➜ Package Manager Console​

2.​ In the black box at the bottom, type:​

bash
CopyEdit
Install-Package EntityFramework

🤖 Now the helper robot (EF) is ready!

🔹 Step 3: Create the Student Model (like a notebook)


1.​ Right-click Models folder ➜ Click Add ➜ Class​

2.​ Name it: Student.cs ➜ Click Add​

3.​ Replace the code with:​


csharp
CopyEdit
using System.ComponentModel.DataAnnotations;

namespace StudentCRUDApp.Models
{
public class Student
{
public int Id { get; set; }

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

public int Age { get; set; }

public string Class { get; set; }


}
}

✏️ Now we made a Student blueprint!

🔹 Step 4: Create a Database Context


This connects your model to the database!

1.​ Right-click Models ➜ Add ➜ Class ➜ Name: StudentContext.cs​

2.​ Paste this:​

csharp
CopyEdit
using System.Data.Entity;

namespace StudentCRUDApp.Models
{
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
}

📦 This says: “Hey, I want to store Students in the database.”

🔹 Step 5: Set Up Database Connection


1.​ Open Web.config file (in the root of the project).​

2.​ Find the <connectionStrings> section and replace it with:​

xml
CopyEdit
<connectionStrings>
<add name="StudentContext"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial
Catalog=StudentDb;Integrated Security=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>

🎯 This creates a local database called StudentDb.

🔹 Step 6: Create the Controller with Views


1.​ Right-click Controllers ➜ Add ➜ Controller​

2.​ Choose: MVC 5 Controller with views, using Entity Framework​

3.​ Click Add​

4.​ Set:​

○​ Model class: Student (StudentCRUDApp.Models)​

○​ Data context: StudentContext (StudentCRUDApp.Models)​

5.​ Click Add​

🎉 Boom! It created everything: Controller + Views for Insert/Edit/Delete!

🔹 Step 7: Run the App! 🚀


1.​ Press F5 (or green Start button)​

2.​ In the browser, go to:​

arduino
CopyEdit
http://localhost:1234/Students

(Your number may be different)


✅ You Can Now:
●​ ➕ Click Create New to add a student​
●​ ✏️ Click Edit to change a student​
●​ ❌ Click Delete to remove a student​
●​ 👀 See the list of all students

====================================================================================
Write a program to send student information form controller to view

🧩 Step 1: Open Visual Studio and Create Project


1.​ Open Visual Studio​

2.​ Click Create a new project​

3.​ Choose: ASP.NET Web Application (.NET Framework) ➜ Click Next​

4.​ Name it: MyStudentApp ➜ Click Create​

5.​ Choose MVC ➜ Click Create​

🎉 You now created your first project! Yay!

🧩 Step 2: Create a Model (Like your Student Notebook 📒)


We are going to make a class to hold student data.

1.​ In Solution Explorer, right-click on the Models folder​

2.​ Click Add ➜ Class​

3.​ Name the file: Student.cs​

4.​ Copy and paste this code:​

csharp
CopyEdit
namespace MyStudentApp.Models
{
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Class { get; set; }
}
}

🧠 This just says: “I have a Student with a Name, Age, and Class.”

🧩 Step 3: Create a Controller (Teacher who gives data 📣)


1.​ In Solution Explorer, right-click on the Controllers folder​

2.​ Click Add ➜ Controller​

3.​ Select: MVC 5 Controller - Empty ➜ Click Add​

4.​ Name it: StudentController​

5.​ Now replace the code inside it with:​

csharp
CopyEdit
using System.Web.Mvc;
using MyStudentApp.Models;

namespace MyStudentApp.Controllers
{
public class StudentController : Controller
{
public ActionResult ShowStudent()
{
// Create a new student
Student s = new Student();
s.Name = "Rahul";
s.Age = 12;
s.Class = "6th";

// Send student info to the view


return View(s);
}
}
}

📌 This code makes a Student object and sends it to the view using View(s).

🧩 Step 4: Create the View (Show data on the screen 🖥️)


1.​ In the controller, right-click on ShowStudent ➜ Click Add View​

2.​ Keep the name as ShowStudent​

3.​ Tick ✔ “Create a strongly-typed view”​

4.​ Choose Model class: Student​

5.​ Click Add​


Now replace the code in ShowStudent.cshtml with this:

html
CopyEdit
@model MyStudentApp.Models.Student

<h2>Student Information</h2>

<p><strong>Name:</strong> @Model.Name</p>
<p><strong>Age:</strong> @Model.Age</p>
<p><strong>Class:</strong> @Model.Class</p>

🎉 This view will now show the student info on the screen.

🧩 Step 5: Run the Project 🚀


1.​ Click the green Start button (or press F5)​

2.​ In the browser, type this:​

arduino
CopyEdit
http://localhost:1234/Student/ShowStudent

(Your number might be different, just copy from the address bar)

✅ Final Output:
You will see:

makefile
CopyEdit
Student Information

Name: Rahul
Age: 12
Class: 6th

=====================================================================================
Write a program for student registration with Crud Operations

🧩 Step 1: Create a New Project in Visual Studio


1.​ Open Visual Studio​

2.​ Click "Create a new project"​

3.​ Choose "ASP.NET Web Application (.NET Framework)"​

4.​ Name it: StudentRegistrationApp​

5.​ Click "Create"​

6.​ Select MVC and click Create​

You’ve now set up your project! 🎉

🧩 Step 2: Create a Model (Student Class)


1.​ Right-click on Models folder ➜ Add ➜ Class​

2.​ Name the class: Student.cs​

3.​ Paste this code:​

csharp
CopyEdit
namespace StudentRegistrationApp.Models
{
public class Student
{
public int Id { get; set; } // Unique ID for each student
public string Name { get; set; } // Student name
public int Age { get; set; } // Student age
public string Class { get; set; } // Student class
}
}

🧠 Model: This is like a student’s information card that holds the student’s details!
🧩 Step 3: Create a Database Context (The helper robot)
1.​ Right-click on Models folder ➜ Add ➜ Class​

2.​ Name it: StudentContext.cs​

3.​ Paste this code:​

csharp
CopyEdit
using System.Data.Entity;

namespace StudentRegistrationApp.Models
{
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
}
}

This allows you to talk to the database and store/retrieve student data! 🧑‍💻

🧩 Step 4: Create a Controller (The teacher 🧑‍🏫)


1.​ Right-click on Controllers folder ➜ Add ➜ Controller​

2.​ Choose: MVC 5 Controller with views, using Entity Framework​

3.​ Model class: Choose Student​


Data context class: Choose StudentContext​

4.​ Name the controller: StudentController​

5.​ Click Add​

Now, Visual Studio has generated all the CRUD actions and views for us! 🎉

🧩 Step 5: Update the Views for Student Registration


In StudentController.cs, you will see methods like Create, Edit, Delete, etc.​
These methods correspond to the views (pages where the user interacts). Let’s look at them:

Create View (Add a New Student)

●​ This is where the user will enter student details (name, age, class).​
●​ Open Views/Student/Create.cshtml and make sure it has this code:​

html
CopyEdit
@model StudentRegistrationApp.Models.Student

<h2>Create Student</h2>

@using (Html.BeginForm())
{
<div>
<label for="Name">Name:</label>
@Html.TextBoxFor(m => m.Name)
</div>
<div>
<label for="Age">Age:</label>
@Html.TextBoxFor(m => m.Age)
</div>
<div>
<label for="Class">Class:</label>
@Html.TextBoxFor(m => m.Class)
</div>
<div>
<button type="submit">Create</button>
</div>
}

This view is where you can add a new student by filling out their information.

Index View (View All Students)

●​ This view shows a list of students.​

●​ Open Views/Student/Index.cshtml and check this code:​

html
CopyEdit
@model IEnumerable<StudentRegistrationApp.Models.Student>

<h2>Student List</h2>

<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Class</th>
<th>Actions</th>
</tr>
@foreach (var student in Model)
{
<tr>
<td>@student.Name</td>
<td>@student.Age</td>
<td>@student.Class</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = student.Id })
@Html.ActionLink("Delete", "Delete", new { id = student.Id })
</td>
</tr>
}
</table>

<a href="@Url.Action("Create")">Add New Student</a>

This view shows a table of all students and gives options to edit or delete them.

🧩 Step 6: Run the Application 🚀


1.​ Press F5 or click the green Start button​

2.​ In your browser, go to:​

arduino
CopyEdit
http://localhost:1234/Student/Index

You should see your list of students!

🧩 Step 7: Try CRUD Operations


●​ Create: Click "Add New Student" and enter student details.​

●​ View: You should see the student’s name, age, and class on the list.​

●​ Edit: Click Edit to change a student’s details.​

●​ Delete: Click Delete to remove a student.​

=====================================================================================
Create a program for Button Group, and write a class for a basic
Button Group

🧩 Step 1: Create a New Project in Visual Studio


1.​ Open Visual Studio​

2.​ Click "Create a new project"​

3.​ Choose "Windows Forms App (.NET Framework)"​

4.​ Name it: ButtonGroupApp​

5.​ Click "Create"​

Now you've created a new Windows Forms application where we can design our Button Group! 🎉

🧩 Step 2: Design the Form with Buttons


1.​ Open the Form Designer by double-clicking on Form1.cs (in the Solution Explorer).​

2.​ Drag and drop 3 buttons from the Toolbox onto the form. They should be named button1, button2,
and button3.​

Now, let’s give each button a label so that we can easily identify them:

●​ Button 1: "Option 1"​

●​ Button 2: "Option 2"​

●​ Button 3: "Option 3"​

You can change the Text property of the buttons to these labels.

🧩 Step 3: Create the Button Group Class


We’ll create a ButtonGroup class to handle which button is selected.

1.​ Right-click on the project in Solution Explorer​

2.​ Choose Add ➜ Class​

3.​ Name the class ButtonGroup.cs​


Now, inside ButtonGroup.cs, we’re going to write a class that will handle the logic of which button is
selected. Here’s the code:

csharp
CopyEdit
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace ButtonGroupApp
{
public class ButtonGroup
{
private List<Button> buttons; // List to store buttons
private Button selectedButton; // The currently selected button

public ButtonGroup()
{
buttons = new List<Button>(); // Initialize the list
selectedButton = null; // No button is selected at the start
}

// Add a button to the group


public void AddButton(Button button)
{
buttons.Add(button);
button.Click += (sender, e) => SelectButton(button); // When clicked,
select the button
}

// Select a button from the group


private void SelectButton(Button button)
{
// Deselect the previous button if there was one
if (selectedButton != null)
{
selectedButton.BackColor = System.Drawing.Color.Empty; // Reset
previous selection
}

// Set the new selected button


selectedButton = button;
selectedButton.BackColor = System.Drawing.Color.LightBlue; // Highlight
selected button
}
}
}
🧠 What This Class Does:
●​ List<Button> buttons: Holds all the buttons that will be in the Button Group.​

●​ Button selectedButton: Tracks which button is currently selected.​

●​ AddButton(Button button): Adds buttons to the Button Group and adds a click event to each button.​

●​ SelectButton(Button button): When a button is clicked, it becomes the selected button, and the
others are deselected.​

🧩 Step 4: Use the Button Group in Form1


Now, let’s go back to Form1.cs and use the ButtonGroup class to manage the buttons.

1.​ Open Form1.cs and add the following code at the top to use the ButtonGroup class:​

csharp
CopyEdit
using ButtonGroupApp; // Import the ButtonGroup class

2.​ In the Form1 class, write the following code to set up the buttons and the button group:​

csharp
CopyEdit
public partial class Form1 : Form
{
private ButtonGroup buttonGroup;

public Form1()
{
InitializeComponent();
buttonGroup = new ButtonGroup(); // Create a new ButtonGroup

// Add the buttons to the ButtonGroup


buttonGroup.AddButton(button1);
buttonGroup.AddButton(button2);
buttonGroup.AddButton(button3);
}
}

🧠 What This Does:


●​ It creates an instance of the ButtonGroup class.​
●​ It adds the buttons (button1, button2, button3) to the ButtonGroup.​

●​ Now, when you click on any button, only one will be highlighted at a time.​

🧩 Step 5: Run the Program 🚀


1.​ Press F5 or click the green Start button.​

2.​ You should see a form with three buttons.​

3.​ When you click on any button, it will highlight that button, and the others will deselect.​

=====================================================================================
Design a Simple one-page template for photo galleries, portfolios,
and more.

🧩 Step 1: Set Up the Project


1.​ Open Visual Studio.​

2.​ Click on Create a new project.​

3.​ Choose ASP.NET Core Web App (Model-View-Controller).​

4.​ Name the project PhotoGalleryMVC (or any name you like).​

5.​ Click Create.​

This will create a basic MVC project for you with all the necessary files!

🧩 Step 2: Set Up the Model


In MVC, a Model is used to represent data. For this photo gallery, our model will represent a Photo with
properties like Title and Image Path.

1.​ Right-click on the Models folder in the Solution Explorer.​

2.​ Click Add ➜ Class.​

3.​ Name the class Photo.cs.​

Now, open the Photo.cs file and add the following code:

csharp
CopyEdit
using System;

namespace PhotoGalleryMVC.Models
{
public class Photo
{
public int Id { get; set; }
public string Title { get; set; }
public string ImagePath { get; set; }
}
}
🧠 What This Code Does:
●​ Id: A unique identifier for each photo.​

●​ Title: The name or description of the photo.​

●​ ImagePath: The file path or URL for the image.​

🧩 Step 3: Create the Controller


The Controller handles requests from the user, processes data, and sends it to the View.

1.​ Right-click on the Controllers folder.​

2.​ Choose Add ➜ Controller.​

3.​ Select MVC Controller - Empty and name it PhotoController.​

Now, open the PhotoController.cs file and update it with the following code:

csharp
CopyEdit
using Microsoft.AspNetCore.Mvc;
using PhotoGalleryMVC.Models;
using System.Collections.Generic;

namespace PhotoGalleryMVC.Controllers
{
public class PhotoController : Controller
{
public IActionResult Index()
{
// Sample list of photos
var photos = new List<Photo>
{
new Photo { Id = 1, Title = "Photo 1", ImagePath =
"/images/photo1.jpg" },
new Photo { Id = 2, Title = "Photo 2", ImagePath =
"/images/photo2.jpg" },
new Photo { Id = 3, Title = "Photo 3", ImagePath =
"/images/photo3.jpg" }
};

return View(photos);
}
}
}
🧠 What This Code Does:
●​ The Index() method sends a list of photos to the View.​

●​ We create a List of Photo objects and add some sample data (photo title and image path).​

●​ The View will display these photos.​

🧩 Step 4: Create the View


The View displays the data sent by the controller. In this case, it will display the photos.

1.​ Right-click on the Views folder, then the Photo folder.​

2.​ Click Add ➜ View.​

3.​ Name the view Index.cshtml (this is the default view for the Index action in PhotoController).​

Now, open the Index.cshtml file and add the following code:

html
CopyEdit
@model IEnumerable<PhotoGalleryMVC.Models.Photo>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Photo Gallery</title>
<link rel="stylesheet" href="~/css/style.css"> <!-- Link to CSS file -->
</head>
<body>

<header>
<h1>My Photo Gallery</h1>
</header>

<section class="gallery">
@foreach (var photo in Model)
{
<div class="photo">
<img src="@photo.ImagePath" alt="@photo.Title">
<h2>@photo.Title</h2>
</div>
}
</section>
</body>
</html>

🧠 What This Code Does:


●​ @model IEnumerable<PhotoGalleryMVC.Models.Photo>: This tells the view that it will receive a
list of Photo objects.​

●​ The foreach loop goes through each photo in the list and displays the image and title.​

●​ @photo.ImagePath and @photo.Title are used to display the image and title of each photo.​

🧩 Step 5: Add Styling (CSS)


Now, let’s make the photo gallery look nice with some simple CSS.

1.​ In the wwwroot folder, create a new folder named css.​

2.​ Inside the css folder, create a new file named style.css.​

3.​ Open style.css and add the following code:​

css
CopyEdit
/* General Styling */
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
color: #333;
text-align: center;
}

/* Gallery Section */
.gallery {
display: flex;
flex-wrap: wrap;
justify-content: center;
margin: 20px;
}

/* Photo Styling */
.photo {
margin: 10px;
border-radius: 10px;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.photo img {
width: 300px;
height: 200px;
object-fit: cover;
border-radius: 10px;
transition: transform 0.3s ease;
}

.photo img:hover {
transform: scale(1.1);
}

h1 {
color: #333;
font-size: 2.5rem;
margin-top: 20px;
}

🧠 What This Code Does:


●​ Flexbox is used to display the photos in a nice, responsive grid.​

●​ Hover effect: When you hover over an image, it grows slightly to make it more interactive.​

●​ Box shadows and rounded corners make the photos look neat and polished.​

🧩 Step 6: Add Images


1.​ Inside the wwwroot folder, create a new folder called images.​

2.​ Add some images (like photo1.jpg, photo2.jpg, etc.) into the images folder.​

Make sure the image paths in PhotoController.cs match the actual filenames of your images.

🧩 Step 7: Run the Application 🚀


1.​ Press F5 or click the Start button in Visual Studio.​

2.​ Your browser should open, showing the photo gallery with your images!
=====================================================================================

You might also like