问题
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