Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call MVC ChildActionOnly Controller Action using jQuery

I have a DropDownListFor that is in a Partial View. On change it fires a jQuery script, but Fiddler shows an HTTP 500 Error:

The action 'LanguageListPartial' is accessible only by a child request.

The calling script:

<script type="text/javascript">
    $(function () {
        $('#SelectedLanguage').on('change', function () {
            var culture = $(this).val();
            $('#test').load("/Account/LanguageListPartial/" + culture, function () {
                location.reload(true);
            });
        });
    });
</script>

I wouldn't want that Controller Action called directly so it is decorated with [ChildActionOnly]. I realize that it's being called directly with the jQuery .load().

Is there a way to keep the ChildActionOnly restriction and still call it from jQuery with the .on('change' ...) event?

like image 909
rwkiii Avatar asked Jun 27 '14 03:06

rwkiii


1 Answers

First : Create a Custom Attribute that supports both ChildActionOnly and Ajax Functionality:

public class AjaxChildActionOnlyAttribute : ActionMethodSelectorAttribute
{
        public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
        {
            return controllerContext.RequestContext.HttpContext.Request.IsAjaxRequest() || controllerContext.IsChildAction;
        }
}

Then : Use above created attribute for your partial View:

[AjaxChildActionOnly]
public PartialViewResult LanguageListPartial(string id)
{
  //Function Logic
}
like image 63
Shawinder Sekhon Avatar answered Oct 05 '22 02:10

Shawinder Sekhon