我一直在尝试在视图中迭代我的ViewData时遇到错误...我甚至尝试将视图强行键入IEnumerable(App.Models.Namespace)并使用Model,但无济于事。要么我因为缺少GetEnumerable方法或者无效的类型转换而出错...我知道我是怎么做的吗?
...模型
public IQueryable<Product> getAllProducts()
{
return (from p in db.Products select p);
}
...控制器
public ActionResult Pricing()
{
IQueryable<Product> products = orderRepository.getAllProducts();
ViewData["products"] = products.ToList();
return View();
}
查看...
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Pricing
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Pricing</h2>
<div>
<select class="product">
<%foreach(var prod in ViewData["products"]){%>
<option><%=prod.Title %></option>
<%} %>
</select><select></select>
</div>
</asp:Content>
答案 0 :(得分:13)
使用演员表尝试:
foreach(var prod in (List<Product>)ViewData["products"])
答案 1 :(得分:2)
foreach (var prod in (ViewData["products"] as IEnumerable<Product>))
我遇到了类似的情况,这对我有用。
答案 2 :(得分:1)
为什么你这样做呢?为什么不这样做:
Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>
在你看来。然后在你的控制器动作中执行:
public ActionResult Pricing()
{
IQueryable<Product> products = orderRepository.getAllProducts();
return View(products.ToList(););
}
然后您根本不必使用ViewData
。
答案 3 :(得分:0)
<%foreach(Product prod in ViewData["products"]){%>
答案 4 :(得分:0)
foreach(var prod in ViewData["products"] as IQueryable<Product>)
答案 5 :(得分:0)
如果你从两个以上的模型中获取列表,并希望在一个列表中显示两个模型,那么你应该像这样使用.. 首先创建你的两个模型是学生,第二个是教师。
// Create Models
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<int> Marks { get; set; }
}
public class Teacher
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
//创建控制器
public ActionResult Index()
{
List<Student> students = new List<Student>()
{
new Student {Id = 1, Name = "Vikas", Address = "Mohali", Marks = new List<int> {90, 23, 46,56} },
new Student {Id = 2, Name = "Rajeev", Address = "Mohali", Marks = new List<int> { 56, 78, 34, 67 }},
new Student {Id = 3, Name = "Ajay", Address = "Delhi", Marks = new List<int> {56, 78, 34, 56}}
};
List<Teacher> teachers = new List<Teacher>()
{
new Teacher {Id = 1, Name = "Arun Nagar", Address = "Delhi"},
new Teacher {Id = 2, Name = "Manish Kumar", Address = "Mohali"}
};
var Querylist = (from student in students
where student.Address == "Mohali"
select student.Name)
.Concat(from teacher in teachers
where teacher.Address == "Mohali"
select teacher.Name);
//get list in ViewBag
ViewBag.DataLIst = Querylist;
//get list in View Data
ViewData["DataLIst1"] = Querylist.ToList();
return View(Querylist.AsEnumerable());
}
//create View "Index.cshtml"
@foreach (var h in @ViewBag.DataLIst)
{
<h3>@h</h3>
}
@foreach (var s in @ViewData["DataLIst1"] as List< string>)
{
<h1>@s</h1>
}