Question

I'm trying to get an Ajax call from a link in a master page.

So I want to specify only the action relative to the current page/controller.

i.e.

 $.ajax({
      url: '/Save',
      type: "GET",
      // .. etc 
 });

I want to call the "Save" action of whatever controller served the page. I thought this would work straight off, but it doesn't appear to. Is there an elegant solution?

Was it helpful?

Solution

If you got this straight into your view, you could do

 $.ajax({
      url: '@Url.Action("Save")',
      type: "GET",
      // .. etc 
 });

If not, and javascript is in external file, you could attach url generated with Url.Action to element as data-? html5 attribute. And then dynamically read that attribute value before doing ajax call.

<input type="text" data-save-action-url="@Url.Action("Save")" />

You should never hardcode url's in asp.net mvc. Always use Url.Action. It inspects your routing configuration when generating urls, and will always return correct value according to it. If you hardcode urls, your application may become unusable when you change routing configuration. And you will have to change every single url in you application manually.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top