【问题标题】:Asp.Net mvc nested actions HTTPPOSTAsp.Net mvc 嵌套动作 HTTPPOST
【发布时间】:2012-08-24 17:13:05
【问题描述】:

我遇到了一个奇怪的问题。我的看法:

@{
   ViewBag.Title = "Index";
}

<h2>Index</h2>
@using(Html.BeginForm())
{
     <input type="submit"  value="asds"/>
}
@Html.Action("Index2")

我的控制器:

public class DefaultController : Controller
{
    //
    // GET: /Default1/

    [HttpPost]
    public ActionResult Index(string t)
    {
        return View();
    }


    public ActionResult Index()
    {
        return View();
    }

    //
    // GET: /Default1/

    [HttpPost]

    public ActionResult Index2(string t)
    {
        return PartialView("Index");
    }

            [ChildActionOnly()]
    public ActionResult Index2()
    {
        return PartialView();
    }
}

当我点击一个按钮时,[HttpPost]Index(string t) 被执行,这很好。但在那之后[HttpPost]Index2(string t) 被执行,这对我来说真的很奇怪,因为我已经发布了Index 的数据,而不是Index2。我的逻辑告诉我[ChildActionOnly()]ActionResult Index2() 而不是HttpPost 一个。

为什么会这样?如何在不重命名 [HttpPost]Index2 操作的情况下覆盖此行为?

【问题讨论】:

    标签: asp.net-mvc http-post child-actions


    【解决方案1】:

    这是默认行为。这是设计使然。如果您无法更改 POST Index2 操作名称,您可以编写一个自定义操作名称选择器,即使当前请求是 POST 请求,也会强制使用 GET Index2 操作:

    public class PreferGetChildActionForPostAttribute : ActionNameSelectorAttribute
    {
        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            if (string.Equals("post", controllerContext.HttpContext.Request.RequestType, StringComparison.OrdinalIgnoreCase))
            {
                if (methodInfo.CustomAttributes.Where(x => x.AttributeType == typeof(HttpPostAttribute)).Any())
                {
                    return false;
                }
            }
            return controllerContext.IsChildAction;
        }
    }
    

    然后用它装饰你的两个动作:

    [HttpPost]
    [PreferGetChildActionForPost]
    public ActionResult Index2(string t)
    {
        return PartialView("Index");
    }
    
    [ChildActionOnly]
    [PreferGetChildActionForPost]
    public ActionResult Index2()
    {
        return PartialView();
    }
    

    【讨论】:

    • 谢谢,我想这会有所帮助。但我真的不明白为什么不将这种行为用作默认值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多