MVC4,C#,从一个View中的两个表中检索数据

时间:2012-11-30 10:39:40

标签: c# asp.net-mvc-4

我是MVC的新手,我使用MVC4而且我是C#的新手。我想从两个表中检索数据:tblProduct和tblCategory在一个视图中。在该视图中,我想从tblCategory获取列" Name"并从tblProduct所有列。

我已经在类tables.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类?这样我就可以将模型栏中的数据发送到View。

public ActionResult Index(){
  //How to define this?
}

应该如何建立视图? @model xx.Models.bar

但我想在视图中使用来自tblProduct的所有列的Foreach循环。 还有一列来自tblCategory。

有人可以帮我这个吗?谢谢!

2 个答案:

答案 0 :(得分:1)

您的索引操作应构建条形类的实例

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循环,因为那时你需要反射,我怀疑该页面的运行速度非常快。

答案 1 :(得分:0)

我认为这两个类都应该是模型,因为它们清楚地表示数据库中的表。不过,班级酒吧我认为不是。我认为你的结构应该像这样组织: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返回到您的视图。