我正在尝试使用 viewbag 将客户列表返回到强类型视图,并且我遇到了一些困难,因为我是 MVC 和 Razor 的新手,任何人都可以就以下问题提供任何建议吗?
我的控制器中有以下代码,
public ViewResult Index()
{
var q = from a in db.Customers
select a;
ViewBag.customer = q;
return View(db.CustomerSites.ToList());
}
我认为这段代码
@foreach (var customer in Model)
{
<tr>
<td>
@ViewBag.customer.CustomerName
<td>
<td>
@customer.UnitNo
</td>
<td>
@Truncate(customer.StreetName, 25)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=customer.Id }) |
@Html.ActionLink("Details", "Details", new { id=customer.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=customer.Id })
</td>
</tr>
}
所以我正在检索客户和客户网站的列表,这些网站被输入到视图中,
@model IEnumerable<trsDatabase.Models.CustomerSite>
我正在尝试从使用的客户列表中提取 CustomerName
@ViewBag.customer.CustomerName
但这会产生一个错误,说“客户”类型不包含客户名称的定义,但它确实如下所示,所以我不确定为什么会发生错误。
namespace trsDatabase.Models
{
public class Customer
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[StringLength(50), Required(ErrorMessage = "Customer name required, please enter a customer name")]
public string CustomerName { get; set; }
[DisplayName("Contact Name")]
[StringLength(50), Required(ErrorMessage = "Primary contact name required, please enter a contact name")]
public string PrimaryContactName { get; set; }
[DisplayName("Secondary Contact")]
public string SecondaryContactName { get; set; }
[DisplayName("Email")]
[StringLength(50), Required(ErrorMessage = "Primary email address is required please enter an email address")]
public string PrimaryEmailAddress { get; set; }
[DisplayName("Secondary Email")]
public string SecondaryEmailAddress { get; set; }
[ScaffoldColumn(false)]
public DateTime RegisteredDate { get; set; }
[DisplayName("Contact No")]
public string PrimaryContactNo { get; set; }
[DisplayName("Secondary Contact No")]
public string SecondaryContactNo { get; set; }
[DisplayName("Waste Carrier Ref")]
public string WasteCarrierRef { get; set; }
[DisplayName("Unit No")]
public string UnitNo { get; set; }
[DisplayName("Street Name")]
[StringLength(50), Required(ErrorMessage = "Street name required, please enter a street name ")]
public string StreetName { get; set; }
[StringLength(50), Required(ErrorMessage = "Town required, please enter a town")]
public string Town { get; set; }
[StringLength(50), Required(ErrorMessage = "County is required, please enter a county")]
public string County { get; set; }
[StringLength(10), Required(ErrorMessage = "Postcode is required, please enter a postcode")]
public string Postcode { get; set; }
public List<CustomerSite> CustomerSites { get; set; }
}
}
更新:
我仍然不能让它做我需要的,我创建了一个主视图模型,其中包括
public IEnumerable <Customer> SomeCustomer { get; set; }
public IEnumerable <CustomerSite> CustomerSites { get; set; }
那么在我看来,
@model IEnumerable<trsDatabase.Models.masterViewModel>
如果我尝试通过使用 for each 键入来访问模型
@foreach (var customer in Model)
当我输入@customer 时。它只会让我访问两个列表,而不是列表中的单个属性。
我以为我可以使用 @customer.CustomerSites.UnitNo 来做到这一点
但我能走的最远的是@customer.CustomerSites
你对我在这里做错了什么有任何想法吗?