Asp.net mvc 4 在asp.net MVC中强制转换ViewData
这是我的控制器代码:Asp.net mvc 4 在asp.net MVC中强制转换ViewData,asp.net-mvc-4,viewdata,Asp.net Mvc 4,Viewdata,这是我的控制器代码: public ActionResult Index() { AccountModel user = new AccountModel(); user.Username = "Jay"; user.Password = "Jay"; ViewData["EmpData"] = user; return View(); } 如何在视图代码中强制转换视图数据[“EmpData
public ActionResult Index()
{
AccountModel user = new AccountModel();
user.Username = "Jay";
user.Password = "Jay";
ViewData["EmpData"] = user;
return View();
}
如何在视图代码中强制转换视图数据[“EmpData”]?在这里,使用此视图代码:
@*Change namespace per your solution.*@
@using WebApplication.Models;
@{
AccountModel emp = (AccountModel) ViewData["EmpData"];
}
//控制器
公共行动结果索引2()
{
IList studentList=新列表();
添加(new Student(){StudentName=“Bill”});
添加(new Student(){StudentName=“Steve”});
添加(new Student(){StudentName=“Ram”});
ViewData[“学生数据”]=学生列表;
返回视图();
}
@*看法*@
@foreach(ViewData[“学生数据”]中的var std)作为
(可数)
{
@std.StudentName
}
要将ViewData转换为视图,只需运行foreach循环,获取ViewData的键并将其转换为包含学生模型的IEnumerable接口
@foreach (var std in ViewData["studentsData"] as
IEnumerable<Mvc_DisplayFormating.Models.Student>)
@foreach(ViewData[“学生数据”中的var std)作为
(可数)
Hello@((ViewData[“EmpData”]作为AccountModel)。用户名)
只需使用返回视图(用户)
并在视图中添加@model user
,我知道这样做会奏效。但是如何使用@model AccountModel强制转换ViewData?如果您不打算将模型传递给视图,那么在视图中使用@model
语句是没有意义的。您可以使用@{var user=ViewData[“EmpData”]作为用户;}
但是可能的重复点是什么
@foreach (var std in ViewData["studentsData"] as
IEnumerable<Mvc_DisplayFormating.Models.Student>)
<span>
Hello @((ViewData["EmpData"] as AccountModel).Username)
</span>