我已經複製您發出去解決它。
- 首先我創建了一個模型。
public class Categories
{
public long CategoryID { get; set; }
public string CategoryName { get; set; }
public Nullable<int> ParentID { get; set; }
}
- 控制器,與索引處理法,其返回分類來索引視圖的一個列表。
代碼片段
public ActionResult Index()
{
List<Categories> li = new List<Models.Categories>()
{
new Categories { CategoryID = 0 , CategoryName = "Work" , ParentID = 1},
new Categories { CategoryID = 0 , CategoryName = "Goods" , ParentID = 2},
new Categories { CategoryID = 0 , CategoryName = "Service",ParentID = 1 },
new Categories { CategoryID = 0 , CategoryName = "Buildings",ParentID = 1},
};
return View(li);
}
- 接下來,我們已經創建了一個靜態方法,其可以是對搜索可訪問的並且該方法採取PARENTID作爲輸入。
通過家長會得到類別名稱,這將返回到 查看。
代碼片段
namespace WebApplication1.Models
{
public static class ManageCategories
{
public static string GetCategoriesbyParentID(int? ParentID)
{
string data = string.Empty;
List<Categories> li = new List<Categories>()
{
new Categories { CategoryID = 0 , CategoryName = "Work" , ParentID = 1},
new Categories { CategoryID = 0 , CategoryName = "Goods" , ParentID = 2},
new Categories { CategoryID = 0 , CategoryName = "Service",ParentID = 1 },
new Categories { CategoryID = 0 , CategoryName = "Buildings",ParentID = 1},
};
data = (from a in li
where a.ParentID == ParentID
select a.CategoryName).FirstOrDefault();
return data;
}
}
}
- 視圖(在其中我們調用靜態方法GetCategoriesbyParentID並傳遞PARENTID到它。)
代碼
@model List<WebApplication1.Models.Categories>
@{
Layout = null;
}
<link href="~/Content/bootstrap.css" rel="stylesheet" />
@{int i = 1;}
<table class="table">
<tr>
<td>CategoryID</td>
<td>Bussiness Category Name</td>
<td>Parent Bussiness Category</td>
</tr>
@foreach (var item in Model)
{
<tr id="[email protected]">
<td>@i</td>
<td>
@Html.DisplayFor(modelItem => item.CategoryName)
</td>
<td> @WebApplication1.Models.ManageCategories.GetCategoriesbyParentID(item.ParentID)</td>
</tr>
i = i + 1;
}
</table>
</div>
輸出: -
如何是一個PARENTID?你的CategoryID很長,但你的ParentID是一個int? –