如何将集合变量(var result)值从Controller传递到MVC5中的View [英] How to pass collection variable (var result) values from Controller to View in MVC5
问题描述
请提供任何解决方案。以下是场景:
控制器
公共ActionResult类别(int id)
{
var result = db.Categories.Where(s => s.DepartmentId == id).Select(x => new {id = x.CategoryId,name = x.CategoryName} ).ToList();
return查看(结果);
}
查看
@model IEnumerable< kshoppingcart.models.category>
模特
命名空间KShoppingCart.Models
{
using System;
使用System.Collections.Generic;
公共部分类别
{
公共类别()
{
this.SubCategories = new HashSet< SubCategory>();
}
public Nullable< int> DepartmentId {get;组; }
public int CategoryId {get;组; }
公共字符串CategoryName {get;组; }
公共虚拟部门部门{get;组; }
public virtual ICollection< SubCategory>子类别{get;组; }
}
}
例如:这里我可以使用变量结果中的值得到count = 2。但是如何使用View显示这些值。
谢谢
JSagar
使用
@ foreach( var item in Model.SubCategories)
{
< span> @ item.XYZ < / span >
// ...继续..对于其他属性。
}
我希望我的预期正确。
如果有的话请回复查询。
谢谢。:)
在视图中您可以使用以下代码
< table >
< tr >
< th > 类别名称< / th >
< th > 部门< / th >
< th > 更多(可以为空白)< / th >
< / tr >
@if(Model!= null)
{
< pre lang = c# >foreach(模型中的catItem)
{
< tr>
< Th> @ catItem.CategoryName< / Th>
< Th> @ catItem.Department< / Th>
< Th>消费崩溃的链接< / Th>
if(catItem.SubCategories!= null)
{
foreach(catItem.SubCategories中的subcatItem)
{
< tr>
<的第i; col name< / Th>
........
}
}
< / Tr>
}
}
Hi,
Please provide any solution. Below is the scenario:
Controller
public ActionResult Category(int id) { var result = db.Categories.Where(s => s.DepartmentId == id).Select(x => new { id = x.CategoryId, name = x.CategoryName }).ToList(); return View(result); }
View
@model IEnumerable<kshoppingcart.models.category>
Model
namespace KShoppingCart.Models { using System; using System.Collections.Generic; public partial class Category { public Category() { this.SubCategories = new HashSet<SubCategory>(); } public Nullable<int> DepartmentId { get; set; } public int CategoryId { get; set; } public string CategoryName { get; set; } public virtual Department Department { get; set; } public virtual ICollection<SubCategory> SubCategories { get; set; } } }
Ex: Here I can get count=2 with values in variable result. But how can I display these values using View.
Thanks
JSagar
Use
@foreach(var item in Model.SubCategories) { <span>@item.XYZ</span> //...Continues.. for other properties. }
I hope I have anticipated correct.
Please post back queries if any.
thanks.:)
In view You can wright follwing code
<table> <tr> <th> Category Name </th> <th> Department </th> <th> More (can be blank) </th> </tr>
@if(Model!=null)
{
<pre lang="c#">foreach(catItem in Model)
{
<tr>
<Th> @catItem.CategoryName </Th>
<Th> @catItem.Department </Th>
<Th> Link for expend collapse </Th>
if(catItem.SubCategories!=null)
{
foreach(subcatItem in catItem.SubCategories)
{
<tr>
<Th> col name </Th>
........
}
}
</Tr>
}
}
这篇关于如何将集合变量(var result)值从Controller传递到MVC5中的View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!