c# - 根据 View 中的预期设置模型

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

目标

根据预期更改模型。

问题

我的 ProductsController 中有一个方法称为 Category .当有人请求此方法时,可能会发生两件事:如果传递给该方法的参数不同于 Daily-Offers ,然后将一种类型的列表传递给 View。如果传递给该方法的参数等于 Daily-Offers ,然后将另一种类型的列表传递给 View。

为了更好地理解,请参阅:

[HttpGet]
public ActionResult Category(string categoryName = null)
{
    int? categoryId = categoryName != "Daily-Offers" ? 
                      Convert.ToInt32(Regex.Match(categoryName, @"\d+").Value) :
                      (int?)null;

    if (categoryName == "Daily-Offers")
    {
        var productsList = Products.BuildOffersList();
        ViewBag.Title = String.Format("Today's deal: ({0})", DateTime.Now);
        ViewBag.CategoryProductsQuantity = productsList.Count;
        ViewBag.CurrentCategory = "Daily-Offers";
        return View(productsList);
    }
    else if (Regex.Match(categoryName, @"\d+").Success && 
             String.Format("{0}-{1}", 
             categoryId, 
             CommodityHelpers.UppercaseFirst
                (CommodityHelpers.GenerateSlug
                     (Categories.GetDetails((sbyte)categoryId).Category_Name))) 
            == categoryName)
    {
        ViewBag.Title = Categories.GetDetails((sbyte)categoryId).Category_Name;
        ViewBag.CategoryProductsQuantity = 
        Categories.GetDetails((sbyte)categoryId).Category_Products_Quantity;
        ViewBag.CurrentCategory = 
           CommodityHelpers.UppercaseFirst(CommodityHelpers.GenerateSlug
           (Categories.GetDetails((sbyte)categoryId).Category_Name));
        return View(Products.BuildListForHome(categoryId, null));
    }
    else
    {
        return View("404");
    }
}

如您所见, View 应准备好接收 IList<Offers>或/和 IList<NormalProducts>我不知道该怎么做。

我已经尝试过的

像这样:

@model if(IEnumerable<BluMercados.Models.Data.getProductsListForHome_Result>) 
       ?: (IEnumerable<BluMercados.Models.Data.getProductsInOfferList_Result>);

但是,当然,没有成功。只是为了说明。

最佳答案

一个 View 实际上应该只有一个模型,因此尝试让一个 View 使用两个不同的模型虽然可行,但不应该这样做。

相反,您可以创建不同的 View 。假设您为 DailyOffers 创建了一个新 View ,它需要 IEnumerable<Offers>作为它的模型。

然后您可以使用 View() 的重载来指定要返回的 View :

return View("DailyOffers", productsList);

但是,如果不这样做,在 DailyOffers 的情况下重定向到不同的操作是否更有意义?所以,你有一个新的 Action :

public ActionResult DailyOffers(...)

而不是 return View(productsList)你这样做:

return RedirectToAction("DailyOffers");

这一切都假设模型彼此之间有足够的不同。如果它们相似,请使用 p.s.w.g 所建议的接口(interface)解决方案。会更有意义。

关于c# - 根据 View 中的预期设置模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17116801/

相关文章:

javascript - 在 div 中绘制 js 响应图

asp.net-mvc-4 - 为什么我无法向 IIS 中托管的 API 发出跨源请求?

razor - Kendo ui Grid 显示 json 而不是网格 Asp .net razor

c# - ViewBag 中的 System.Random 不显示为字符串?

c# - 我可以更改默认配置文件吗?

c# - 从 Func<bool, T> 或类似的 lambda 中提取信息

javascript - 如何在 MVC 中使用检查的 ID 创建数组

razor - 有没有办法在构建时在类库项目中启用编译 cshtml 模板?

带有 MahApps 的 C# WPF 应用程序无法在 Windows 2008 中显示

c# - 如何在 web api 项目中执行 Routes.IgnoreRoute?