我有这一行:
@Html.ActionLink("Discounts", "ListDiscounts", "Product", null, new { @class = ViewBag.Discount })
ListDiscounts是:
public ViewResult ListDiscounts(int nrProducts = 5)
{
ViewBag.Discount = "selected";
ProductsListViewModel model = new ProductsListViewModel
{
Products = repository.Products
.Where(p => p.Discount != false)
.Take(nrProducts)
};
return View(model);
}
呈现菜单的视图(我的单独折扣也将在哪里)
@model IEnumerable<string>
@Html.ActionLink("Home", "List", "Product")
@foreach (var link in Model) {
@Html.RouteLink(link, new
{
controller = "Product",
action = "List",
category = link,
page = 1
},
new
{
@class = link == ViewBag.SelectedCategory ? "selected" : null,
})
}
ListDiscounts.cshtml
@model Sportsstore.WebUI.Models.ProductsListViewModel
@{
ViewBag.Title = "ListDiscounts";
}
<h2>Discounts available</h2>
@foreach (var p in Model.Products)
{
Html.RenderPartial("ProductSummary", p);
}
我试图将选定的课程添加到我的&#39; a&#39;视图中的元素,但这不起作用。单击“折扣”链接时,ViewBag属性仍为空。
与ListDiscounts相关联的视图不是ActionLink行来自的视图(它们与具有部分视图的视图分开)但是从我理解的ViewBag特征具有某种全局状态这应该有用吗?
关于这里有什么问题的任何想法?
编辑:使用MVC 4
答案 0 :(得分:2)
我相信有些东西你没有告诉我们这是问题所在。也许你只在post方法中填充了ViewBag,而不是你的get方法。我创建了一个测试应用程序,非常密切地模拟你的应用程序,它工作正常。
控制器
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ViewResult Index()
{
ViewBag.Discount = "selected";
return View();
}
[HttpPost]
public ViewResult Index(int nrProducts = 5)
{
var model = new ProductsListViewModel{Products = "stuff"};
ViewBag.Discount = "selected";
return View(model);
}
}
}
查看
@model MvcApplication1.Models.ProductsListViewModel
@Html.ActionLink("Discounts", "Index", "Home", null, new { @class = ViewBag.Discount })
@{ Html.RenderPartial("ViewPage1");}
@using (Html.BeginForm())
{
<input type="submit" />
}
<强>部分强>
@Html.ActionLink("Discounts", "Index", "Home", null, new { @class = ViewBag.Discount })
当我查看源时,两个链接都具有我期望的类。在我点击链接后,他们也有预期的课程。因此,我相信您不会在Get和/或Post控制器方法
上填充视图包答案 1 :(得分:0)
如果你确定你在viewbag属性中有价值而不是
@class = ViewBag.Discount
试试
@class = @ViewBag.Discount
并查看是否有效
答案 2 :(得分:0)
您只需尝试以下代码即可。更改Viewbag名称并尝试。
@Html.ActionLink("Discounts", "ListDiscounts", "Product", null, new { @class = ViewBag.CssDiscount })
public ViewResult ListDiscounts(int nrProducts = 5)
{
ViewBag.CssDiscount = "selected";
ProductsListViewModel model = new ProductsListViewModel
{
Products = repository.Products
.Where(p => p.Discount != false)
.Take(nrProducts)
};
return View(model);
}