[英]MVC4, C#, retrieve data from two tables in one View
我是MVC的新手,我使用MVC4,而C#的新手。 我想在一個視圖中從兩個表中檢索數據:tblProduct和tblCategory。 在該視圖中,我想從tblCategory列獲取“名稱”列,並從tblProduct獲取所有列。
我首先在類table.cs中的代碼中定義了表:
public class tblCategory
{
//Primary Key
[Key]
[ScaffoldColumn(false)]
public int CategoryId { get; set; }
[MaxLength(160)]
public string Name { get; set; }
etc...
}
public class tblProduct {
//Primary Key
[Key]
[ScaffoldColumn(false)]
public int ProductId { get; set; }
//Foreign Key
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public virtual tblCategory tblCategorys { get; set; }
[MaxLength(500)]
public string MainImageFileName { get; set; }
[MaxLength(160)]
public string Name { get; set; }
ect...
}
我的模型類bar.cs:
Namespace xx.Models
public class bar {
public tblProduct product { get; set; }
public tblCategory category { get; set; }
}
我如何在Controller中定義Index類? 這樣我就可以將數據從模型欄發送到視圖中。
public ActionResult Index(){
//How to define this?
}
以及如何建立視圖? @model xx.Models.bar
但是我想在我的視圖中為tblProduct中的所有列使用一個Foreach循環。 和tblCategory中的一列。
有人可以幫我嗎? 謝謝!
您的Index動作應建立您的Bar類的實例
public ActionResult Index(){
var b = new bar();
b.product = some loading code;
b.category= some loading code;
return View(b);
}
您的Index.cshtml需要使用相同模型的實例
@model ProjectName.xx.Models.bar
<div class="editor-label">
@Html.LabelFor(model => model.category.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.category.Name)
@Html.ValidationMessageFor(model => model.category.Name)
</div>
@* just duplicate this once for each property you want from product *@
<div class="editor-label">
@Html.LabelFor(model => model.product.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.product.Name)
@Html.ValidationMessageFor(model => model.product.Name)
</div>
我不會在產品的屬性上使用for循環,因為那樣的話您需要反思,而且我懷疑該頁面的運行速度會很快。
我認為這兩個類都應該是模型,因為它們顯然是數據庫中表的表示。 但是我認為不是班級吧。 我認為您的結構應該這樣組織:product(模型類),category(模型類)= bar(模型集合類)。 因此,不要將兩個類都添加為Bar類的屬性,而應定義將包含這些類但將這些類與公共接口(即IViewModel)綁定的字典。
public interface IViewModel{
string name {get;set;}
}
public class TblProduct: IVievModel{
/// your code
}
public class TblCategory: IVievModel{
/// your code
}
public class Bar{
private Dictionary<string, IViewModel> viewModels = new Dictionary<string,IViewModel>();
}
現在,在您的ActionResult方法中,您只需將這兩個類添加到字典中,然后將此類Bar返回到您的視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.