【问题标题】:MVC3 Why do I get "Child actions are not allowed to perform redirect actions" error?MVC3 为什么我会收到“不允许子操作执行重定向操作”错误?
【发布时间】:2012-03-20 15:16:50
【问题描述】:

我有一个动作列表

    //[HttpGet] (will come back to that!)
    public ViewResult List(int page = 1)
    {
        //blah blah blah
        return View(viewModel);
    }

在它看来我们渲染动作:

@{        
    Html.RenderAction("UpdateSearch");
}

动作定义:

[ChildActionOnly]
[HttpGet]
public PartialViewResult UpdateSearch()
{
    // do something and display a form in view
    return PartialView(so);
}

[HttpPost]
public RedirectToRouteResult UpdateSearch(Options searchOptions)
{
    // do something and redirect to List
    return RedirectToAction("List");
}

我得到:每次有人提交表单时,子操作都不允许执行重定向操作异常。我是 MVC3 的新手,但看起来重定向也是一个 POST,因为如果未注释 List 方法上面的 [HttpGet],则会发生“找不到资源”。

如何更改重定向时的 Http 方法或者我做错了什么?我确实尝试过 Bing 它,但没有成功。

【问题讨论】:

    标签: asp.net-mvc-3 redirect http-method child-actions


    【解决方案1】:

    重定向信息存储在响应标头中。但是,在运行子操作时已经发送了响应,因此无法写入标头。

    简而言之,除了在客户端使用 javascript 之外,没有其他方法可以从子操作执行重定向。

    【讨论】:

    • 这是有道理的,但我的示例中的重定向不是通过带有 [ChildActionOnly] 注释的方法完成的。问题是当 [HttpPost] UpdateSearch 重定向到 List 时,它使用 POST 重定向,因此 [HttpPost] 方法被(试图)用于视图中的部分生成。我可以使用 RouteValueDictionary 来更改它吗?
    • 向我们展示部分视图的内容。问题可能在于 BeginForm 中的路线定义错误,但我无法在没有看到视图的情况下判断。
    • 你是对的。要修复它,只需在 UpdateSearch 视图(Get,Child version)中将操作参数添加到 BeginForm 方法,因此从:/@using (Html.BeginForm()) { 更改为:/@using (Html.BeginForm(" UpdateSearch")) { 解决了这个问题。你能解释原因吗?
    • BeginForm 不带参数是指主动作的当前路由,而不是子动作。因此发生的事情是 UpdateSearch(Options searchOptions) 方法被称为子操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多