ajbeaven
ajbeaven

Reputation: 9582

ASP.NET MVC: Action that is only called by other actions

I want to make a GET action that only runs if it is called by another action, so not if the user types the URL in the address bar. What can I check to determine whether this is the case?

Upvotes: 3

Views: 3409

Answers (3)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38508

Make that action's acces modifier private. Since it's a private method, it's not an action method and cannot be called by URL:

private ActionResult PrivateAction()
{
    return View("SomeView");
}

Then call it from an action method:

public ActionResult SomeAction()
{
    if(someCondition)
        return PrivateAction();
}

Upvotes: 12

QMaster
QMaster

Reputation: 3904

@Andras Decorating actions with [ChildActionOnly] prevents from calling action via ajax and that's necessary in some scenarios. About @ajbeaven question you right but in ajax calling situation I think that is best to decorate action with [HttpPost] attribute.

Good Luck

Upvotes: 0

Andras Vass
Andras Vass

Reputation: 11638

You may decorate the action with the ChildActionOnlyAttribute.

  [ChildActionOnly]
  public ActionResult Menu() {
    var menu = GetMenuFromSomewhere();
      return PartialView(menu);
  }

You may then use the RenderAction() and Action() Html helpers as usual and the action cannot be called by URL.

These are new to MVC 2, but from the tags I assume that you are already using that.

Sample: http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx

Upvotes: 15

Related Questions