簡體   English   中英

MVC4 Ajax請求

[英]MVC4 Ajax Request

這是我的控制器課

[HttpGet]
    public ActionResult ContactUs()
    {
        if (Request.IsAjaxRequest())
        {
            return PartialView("_ContactUs");
        }

        return View();
    }

我的問題返回PartialView(“ _ ContactUs”); 沒有在MVC4中執行,直接返回View(); 正在執行

您需要使用操作方法選擇器來區分Ajax請求和非Ajax請求。 因此,實現ActionMethodSelectorAttribute並用該屬性裝飾您的操作方法(true)。 請參見下面的示例代碼。

[HttpGet]
[MyAjax(true)]
public ActionResult ContactUs()
{
    if (Request.IsAjaxRequest())
    {
        return PartialView("_ContactUs");
    }

    return View();
}

//.. 

public class MyAjaxAttribute : ActionMethodSelectorAttribute
    {
        private readonly bool _ajax;
        public AjaxAttribute(bool ajax)
        {
            _ajax = ajax;
        }

        // Determines whether the action method selection is valid for the specified controller context
        public override bool IsValidForRequest(
                               ControllerContext controllerContext,
                               MethodInfo methodInfo)
        {
            return _ajax == controllerContext.HttpContext.Request.IsAjaxRequest();
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM