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 ?

5
  • Just use return View(user); and add @model user in the view Commented May 5, 2016 at 12:46
  • I know it would work that way. But how to cast ViewData using @model AccountModel ? Commented May 5, 2016 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 Commented May 5, 2016 at 12:50
  • asp.net/mvc/overview/getting-started/introduction/… Commented May 5, 2016 at 12:53
  • Possible duplicate of How to handle ViewData type casting in MVC Commented May 5, 2016 at 13:06

4 Answers 4

3

Here you go, use this in view code:

@*Change namespace per your solution.*@
@using WebApplication.Models;
@{
    AccountModel emp = (AccountModel) ViewData["EmpData"];
}
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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>)

Comments

0
<span>
    Hello @((ViewData["EmpData"] as AccountModel).Username)
</span>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.