2

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 ?

iJade
  • 23,144
  • 56
  • 154
  • 243
  • Just use `return View(user);` and add `@model user` in the view –  May 05 '16 at 12:46
  • I know it would work that way. But how to cast ViewData using @model AccountModel ? – iJade May 05 '16 at 12:47
  • If your not going to pass a model to the view, then there is no point having a `@model` statement in the view. You could use `@{ var user = ViewData["EmpData"] as user; }` but what would be the point –  May 05 '16 at 12:50
  • http://www.asp.net/mvc/overview/getting-started/introduction/accessing-your-models-data-from-a-controller – G. Stoynev May 05 '16 at 12:53
  • Possible duplicate of [How to handle ViewData type casting in MVC](http://stackoverflow.com/questions/2685723/how-to-handle-viewdata-type-casting-in-mvc) – G. Stoynev May 05 '16 at 13:06

4 Answers4

3

Here you go, use this in view code:

@*Change namespace per your solution.*@
@using WebApplication.Models;
@{
    AccountModel emp = (AccountModel) ViewData["EmpData"];
}
Abhi
  • 33
  • 1
  • 4
1
   // 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>
0

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>)
Rohan Rao
  • 2,505
  • 3
  • 19
  • 39
0
<span>
    Hello @((ViewData["EmpData"] as AccountModel).Username)
</span>
Ekus
  • 1,679
  • 21
  • 17