目标
根据预期更改模型。
问题
我的 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/