How to call MVC ChildActionOnly Controller Action using jQuery

三世轮回 提交于 2021-02-07 12:44:11

问题


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?


回答1:


No, you cant do that. The whole point of the ChildActionOnly attribute is to prevent it being invoked as a result of a user request.




回答2:


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
}


来源:https://stackoverflow.com/questions/24443531/how-to-call-mvc-childactiononly-controller-action-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!