gpt4 book ai didi

asp.net-mvc - 如何使用 asp.net MVC razor 将两个模型组合成一个模型并将其传递给 View

转载 作者:行者123 更新时间:2023-12-01 22:36:29 24 4
gpt4 key购买 nike

我正在尝试将两个模型(tblCategories 和 tblProducts)组合成一个模型并将其传递给 View 。但是没办法。

tblCategory.cs 是主要模型有以下数据

namespace ScaffoldCreate.Models
{
using System;
using System.Collections.Generic;

public partial class tblCategory
{
public int CategoryId { get; set; }
public string Name { get; set; }
}
}

tblProduct.cs

public partial class tblProduct
{
public int ProductId { get; set; }
public int ProductName { get; set; }
public int CategoryId { get; set; }
public int SubCategoryId { get; set; }
public string ProductDescription { get; set; }
public string StockStatus { get; set; }
public IList<tblCategory> CategoryName { get; set; }
}
}

我试图将 tblCategory 放入 tblProduct 并尝试在索引页中检索它,如下所示:

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.CategoryName.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductId)
</td>
<td>
@Html.DisplayFor(modelItem => item.CategoryId)
</td>
<td>
@Html.DisplayFor(modelItem => item.SubCategoryId)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductDescription)
</td>
<td>
@Html.DisplayFor(modelItem => item.StockStatus)
</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>
}

但是,我无法通过它。谁能帮我解决这个问题?

最佳答案

将 ViewModel 用于将解决您的问题的 View ::

class CommonViewModel 
{

Model1 model1;
Model2 model2;
}

其中 Model1 和 Model2 是您的模型 aS::

public class Model1 
{
public int ID{get;set;}
public string Name{get;set;}
}

和 Model2 一样::

public class Model2 
{
public int ID{get;set;}
public string Name{get;set;}
}

在您的 View 中,您将其作为强类型::

@model ProjectName.CommonViewModel

在这里您可以将 Model1 用作::您也可以将模型传递给另一个局部 View ,也可以在同一 View 中使用::

@Html.Partial("_PartialViewName",Model.Model1)

@foreach (var item in Model.Model2)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CategoryName.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductId)
</td>
<td>
@Html.DisplayFor(modelItem => item.CategoryId)
</td>
<td>
@Html.DisplayFor(modelItem => item.SubCategoryId)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductDescription)
</td>
<td>
@Html.DisplayFor(modelItem => item.StockStatus)
</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>
}

关于asp.net-mvc - 如何使用 asp.net MVC razor 将两个模型组合成一个模型并将其传递给 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22368726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com