I am using ajax to load a partial view in order to add/edit a row in a kendo grid. When I press an edit button in the row I want to also not allow the user to directly call the Home/AddModify
action from the browser.
If I put [ChildActionOnly]
to my "AddModify" action it does not let me load the partial view
because everything is in the ajax call, and I do not want to have it in the view somewhere like a @Html.Action("Home/AddModify",model)
. I also do not want to load it from the beginning when the page is loaded.
Can I call the partial view so it is only viewed on demand (dynamically)?
What you need is an AJAX only attribte Take a look at this question
Declare it like
public class AjaxOnlyAttribute : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
return controllerContext.RequestContext.HttpContext.Request.IsAjaxRequest();
}
}
and use it like
[AjaxOnly]
public ActionResult ajaxMethod()
{
}
You can use the IsAjaxRequest extension method on HttpRequestBase.
It doesn't prevent every user to call it (you cannot prevent them until it is publicly accessible) (because they can modify the headers to whatever), but for general purpose it may be good for you.
You can make an actionfilter:
public class RestrictToAjaxAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
throw new InvalidOperationException("This action is only available via ajax");
}
}
}
and put this attribute on top of your action:
[RestrictToAjax]
public ActionResult YourAction()
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With