ASP.NET MVC嵌套动作HTTPPOST

3

i ve got a weird problem. My view :

@{
   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操作的情况下覆盖此行为?
1个回答

2

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

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();
}

谢谢,我认为这可能会有所帮助。但我真的不明白为什么这种行为不作为默认行为。 - armless-coder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接