简体   繁体   中英

MVC4 Ajax Request

This is my Controller class

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

        return View();
    }

My problem return PartialView("_ContactUs"); is not getting executing in MVC4 directly return View(); is getting executed

You need to use an action method selector to differentiate between Ajax and non-Ajax requests. So, implement ActionMethodSelectorAttribute and decorate your action method with that attribute (true). See sample code below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM