Reputation: 23801
Here is my controller code :
public ActionResult Index()
{
AccountModel user = new AccountModel();
user.Username = "Jay";
user.Password = "Jay";
ViewData["EmpData"] = user;
return View();
}
How can I cast the ViewData["EmpData"]
in the view code ?
Upvotes: 2
Views: 5266
Reputation: 1880
<span>
Hello @((ViewData["EmpData"] as AccountModel).Username)
</span>
Upvotes: 0
Reputation: 11
To cast the ViewData into a view you can simply run a foreach loop taking the ViewData's key and casting it into IEnumerable interface that contains the Student Model.
@foreach (var std in ViewData["studentsData"] as
IEnumerable<Mvc_DisplayFormating.Models.Student>)
Upvotes: 0
Reputation: 11
// Controller
public ActionResult Index2()
{
IList<Student> studentList = new List<Student>();
studentList.Add(new Student(){ StudentName = "Bill" });
studentList.Add(new Student(){ StudentName = "Steve" });
studentList.Add(new Student(){ StudentName = "Ram" });
ViewData["studentsData"] = studentList;
return View();
}
@* View *@
@foreach (var std in ViewData["studentsData"] as
IEnumerable<Mvc_DisplayFormating.Models.Student>)
{
<li>
@std.StudentName
</li>
}
</ul>
Upvotes: 1
Reputation: 33
Here you go, use this in view code:
@*Change namespace per your solution.*@
@using WebApplication.Models;
@{
AccountModel emp = (AccountModel) ViewData["EmpData"];
}
Upvotes: 3