如何在 MVC 中 return 两个模型?

How to return two models in MVC?

我有这个函数将在控制器中调用:

public EditViewModel PostEditViewModel(EditViewModel model)
    {            
        using (var db = new NorthwindEntities())
        {
            var prod = db.Products.Where(x => x.Id == model.Id).Single();
            {
                prod.Id = model.Id;
                ...
                //I need something like this:
                //prod.CategoryID = model.CategoryList.CatId
                //but obviously intellisense tells me that after the dot of CategoryList, only methods of that list can be called.
                db.SaveChanges();
            }

这是我的 ViewModel:

    public int Id{ get; set; }
    ...
    public IEnumerable<Categories> CategoryList { get; set; }

    public class Categories {
    public int ProdId { get; set; }
    public int? CatId { get; set; }
    public string CatName { get; set; }
    }

如何通过我的 EditViewModel 调用 CategoryList,以便我可以通过 HTML.DropdownList 编辑特定产品的类别?

如果您的产品模型有 CategoryId 属性(我只是在您的问题中看不到它)并且您使用的是强类型视图 您总是可以使用 DropDownListBoxFor() 的重载帮手:

@Html.DropDownListFor(
    x => x.CategoryId,
    new SelectList(Model.CategoryList, "CatId", "CatName")
)

但实际上我 推荐 你在 ViewModels 中使用 SelectListItem 用于你所有的下拉菜单,因为这是非常糟糕的做法 - 将域实体放在你的 View

你的 ViewModel 会像:

public int Id { get; set; }
public int CategoryId { get; set; } 
...
public IEnumerable<SelectListItem> CategoryList { get; set; }

在 View 上你可以这样做:

@Html.DropDownListFor(x => x.CategoryId, Model.CategoryList)

在您的 GET ViewModel Controller 中,您可以像这样初始化 CategoryList

        model.CategoryList = db.Categories.OrderBy(x => x.Name)
            .Select(x => new SelectListItem
            {
                Text = x.Name,
                Value = x.Id.ToString()
            });

它确实可以帮助您使视图更清晰。

看起来 CategoryList 用于填充 DropDownList 中的项目,而 CatId 是视图模型上的 属性,用于捕获所选类别的 ID 值。

如果是这种情况,您可以像这样分配它:

if (model.CatId.HasValue) 
{
  prod.CategoryID = model.CatId.Value;
}

如果我没记错并且我理解你的话,你应该在这个 class 中创建 class EditViewModel 创建字段:

public int Id{ get; set; }
...
public IEnumerable<Categories> CategoryList { get; set; }

接下来,在您的控制器中,您应该使用以下代码:

var prod = db.Products.Where(x => x.Id == model.Id).Single();
            {
                prod.Id = model.Id;
                ...
                prod.CategoryID = model.CategoryList.Select(m => m.CatId)
                //but Select returned the List of CatId, I suggest thet prod.CategoryID is List               
            }
db.SaveChanges();