11

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

fassetar
  • 615
  • 1
  • 10
  • 37
king julian
  • 111
  • 2
  • 9

2 Answers2

19

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

}
Community
  • 1
  • 1
U.P
  • 7,357
  • 7
  • 39
  • 61
3

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()
{
}
Peter Porfy
  • 8,921
  • 3
  • 31
  • 41
  • i was aware of that in pluralsight tutorial about mvc 4,and i didn't think of this.It's enough for me to use the IsAJaxRequest,putting a message or an error page when is not ajax was ok.Many thanks for the ideea. – king julian Mar 19 '13 at 08:16
  • if i want to return a html page instead of throwing an error,how can i do that? – king julian Mar 19 '13 at 10:49
  • for the moment i used a filtercontext.Httpcontext.Response.Redirect("/Infrastructure/InvalidOperation") – king julian Mar 19 '13 at 11:07
  • you can assign an ActionResult instance to filterContext.Result – Peter Porfy Mar 19 '13 at 14:29