MVC3 - 从[无为]控制器事件重定向 [英] MVC3 - Redirect from a [NonAction] Controller event
问题描述
比方说,我是一个[无为]控制器事件中,想出来重定向到首页?什么是这样做的最简单的方法是什么?
Let's say I'm inside a [NonAction] controller event and would like to redirect out to the Home Page? What's the easiest way to do so?
[NonAction]
private ShoppingCartModel PrepareShoppingCartModel(ShoppingCartModel model,
IList<ShoppingCartItem> cart)
{
if (cart == null)
throw new ArgumentNullException("cart");
if (model == null)
throw new ArgumentNullException("model");
if (cart.Count == 0)
return model;
...bla bla bla (lots of code)
}
现在3号线,如果Cart.Count如果= 0,而不是返回一个空的模式,即得到视图显示空的,我宁愿重定向到首页。
Now on the 3rd line, if the Cart.Count if = 0, instead of returning a empty model, that gets the View Display empty, I would rather redirect to the Home Page.
我不能使用return RedirectToAction()使编译器给了我以下错误:
I cannot use return RedirectToAction() cause the compiler gives me the following error:
无法隐式转换类型'System.Web.Mvc.RedirectToRouteResult
以Web.Models.ShoppingCart.ShoppingCartModel
Cannot implicitly convert type 'System.Web.Mvc.RedirectToRouteResult' to 'Web.Models.ShoppingCart.ShoppingCartModel'
问:结果
那么什么是退出[无为]控制器程序的正确方法?
QUESTION:
So what's the right way to exit a [NonAction] Controller procedure?
推荐答案
返回类型应该是的ActionResult 和您应该返回,而不是唯一模式视图(模型)。您code应该像下面。
Return type should be ActionResult and you should return View(model) instead of only model. Your code should be like below.
[NonAction]
private ActionResult PrepareShoppingCartModel(ShoppingCartModel model,
IList<ShoppingCartItem> cart)
{
if (cart == null)
throw new ArgumentNullException("cart");
if (model == null)
throw new ArgumentNullException("model");
if (cart.Count == 0)
return View(model);
...bla bla bla (lots of code)
}
这篇关于MVC3 - 从[无为]控制器事件重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!