Monday, October 2, 2023

Passing Data from Controller to View using ViewData in ASP.NET MVC

 


In this blog post, we will explore how to pass data from a controller to a view using ViewData in an ASP.NET MVC project.

#Model

namespace hello_World.Models

{

    public class student

    {

        public string StudentName { get; set; }

        public int Age { get; set; }

    }

}

The code above defines a simple student model class with properties for StudentName and Age.

#Controller

public IActionResult Index()

{

    student student = new student();

    student.Age = 20;

    student.StudentName = "Tanvir";

    return View(student);

}

In the controller's Index action method, we create an instance of the student class, set the Age and StudentName properties, and pass the student object to the View method.

#View

@model hello_World.Models.student;

@{

    ViewData["Title"] = "Home Page";

}

 <div class="text-center">

    <p>Your name is @Model.StudentName. You are @Model.Age years old.</p>

</div>

The view is strongly typed to the student model using the @model directive. We access the StudentName and Age properties of the model using @Model.StudentName and @Model.Age respectively.

No comments:

Post a Comment

Passing Data from Controller to View using ViewData in ASP.NET MVC

  In this blog post, we will explore how to pass data from a controller to a view using ViewData in an ASP.NET MVC project. #Model names...