【发布时间】:2013-09-11 04:08:15
【问题描述】:
我通常使用 SQL 和 SSRS,并且是 C# 新手,正在处理我的第一个 MVC 项目。
我的目标是创建一个页面,该页面显示一个包含父项及其关联子记录的表格 - 没有父项为每个子值重复。
Column1父表的主键
第 2 列父表中的名称
第 3 列子名列表
为了实现这一点,我尝试创建一个模型视图。
我相信我犯了许多与代码放置有关的错误
模型视图
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace SupplierItemTest.Models
{
public class VM_Trade
{
[Required]
[Display(Name = "Tax Info")]
public virtual string TaxpayerID { get; set; }
[Required]
[Display(Name = "Entity Name")]
public virtual string Supplier { get; set; }
[Required]
[Display(Name = "Trading Names")]
public virtual string SupplierTradingName1 { get; set; }
[Required]
[Display(Name = "Supplier Number")]
public virtual string EhSupplierNumber { get; set; }
}
}
控制器视图
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SupplierItemTest.Models;
namespace SupplierItemTest.Controllers
{
public class TradingNameController : Controller
{
private SupplierItemEntities db = new SupplierItemEntities();
//
// GET: /TradingName/
public ActionResult Index()
{
var Trade_View =
from s in db.Suppliers
join st in db.SupplierTradingNames on s.TaxpayerID equals st.TaxpayerID
join sn in db.EhSuppliers on s.TaxpayerID equals sn.TaxpayerID
orderby s.TaxpayerID
select new VM_Trade
{
SupplierTradingName1 = st.SupplierTradingName1,
TaxpayerID = s.TaxpayerID,
Supplier = s.SupplierName,
EhSupplierNumber = sn.EhSupplierNumber
};
return View(Trade_View.ToList());
查看
@model IEnumerable<SupplierItemTest.Models.VM_Trade>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.TaxpayerID)
</th>
<th>
@Html.DisplayNameFor(model => model.Supplier)
</th>
<th>
@Html.DisplayNameFor(model => model.EhSupplierNumber)
</th>
<th>
@Html.DisplayNameFor(model => model.SupplierTradingName1)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.TaxpayerID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Supplier)
</td>
<td>
@Html.DisplayFor(modelItem => item.EhSupplierNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.SupplierTradingName1)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
- 最初我尝试将 IEnumerable 放在 View Model 中,我的控制器 LINQ 返回以下内容
错误“无法将类型'string'隐式转换为'Systen.Collections.Generic.IEnumerable
我希望有人能告诉我:
- 如果模型视图和控制器的结构不正确
- 如何为父列返回单个值
根据我的阅读,我有以下错误:
- 应在模型视图中使用 IEnumerable
- LINQ 不应使用连接,因为它们是数据库中的关系
- 视图不应包含 IEnumerable
- 我不知道如何从父列返回单个值并为子行返回多个值。
我已经阅读了几天,似乎可以做任何事情。
【问题讨论】:
标签: c# asp.net-mvc linq