Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MVC3 childactiononly attribute with ajax

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)?

like image 205
king julian Avatar asked Mar 18 '13 09:03

king julian


2 Answers

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()
{

}
like image 136
U.P Avatar answered Sep 25 '22 10:09

U.P


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()
{
}
like image 27
Peter Porfy Avatar answered Sep 21 '22 10:09

Peter Porfy