We can pass the Data from Controller to View in 2 ways.

1. ViewData

Example for Single value data

Action Controller Code: In controller write below code to save value in ViewData.

public class HomeController : Controller
{
    public ActionResult Index()
    {
    ViewData[“MyViewName”] =” Type string to pass here”;
        return View();
    }
}

To show it in the Razor page, we can write @ViewData[“Key”]

Index.cshtml View : In your cshtml to show data in front end write below line of code

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div> 
@ViewData[“MyViewName”]
</div>

To save data in list

Controller Action Code:

public ActionResult About()
{
IList<Employee> empList = new List<Employee>();
    empList.Add(new Employee(){ Name = "Satya" });
    empList.Add(new Employee(){ Name = "Rij" });
    empList.Add(new Employee(){ Name = "Ram" });
   ViewData[“ListEmployee”]=empList;
   return View();
}

Then, in View we need to set the value of ViewData[“ListItems”] as the collection of integer list.

In your About.cshtml View you can get saved data by

@{
    ViewBag.Title = "About";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@foreach (var emp in ViewData["ListEmployee"] as IList<Employee>)
{
    <li>
        @emp.Name
    </li>
}

2. ViewBag : Another method is to save data in ViewBag

 ViewBag is easier and simple way. It accepts data as objects so we can set any type of data.

Controller Code

public ActionResult Demo()
{
ViewBag.MyViewBagName=”Send the data that you wanted ”;
return View();
}

In your Demo.cshtml View to get data from ViewBag you can do in below way.

@{
    ViewBag.Title = "Demo";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
@ViewBag.MyViewBagName
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *