Klaus Nji
Klaus Nji

Reputation: 18847

Call ASP.NET MVC controller action from seperate javascript file

What url syntax should I be using to ensure controller actions are properly resolved in a jQuery ajax call? For example, the following syntax to invoke Method1 on HomeController works while running site in Visual Studio:

 $.ajax({
             type: 'GET',
             url: "Home/Method1?lparam1=" + 1+ "&param2=" + 2,  // my problem
             dataType: 'json',
             cache: false,             
             success: function(){ alert("success");}
         });

But when I deploy site on IIS, I get HTTP 404 telling me controller actions can not be resolved.

TIA.

Upvotes: 1

Views: 2521

Answers (2)

veblock
veblock

Reputation: 1924

Just change the url line to:

url: "/Home/Method1?lparam1=" + 1+ "&param2=" + 2,

Upvotes: 0

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107508

I would let MVC generate the link for you:

url: '@Url.Action("Method1", "Home")?lparam1=' + encodeURIComponent(1) + ... 

If your JS in an external file, you could set a global variable with the URL in your page and let the external file read it. Also, if your VS and IIS urls are different, you can give you site a Virtual Directory name in the project properties so that it matches your IIS directory, or better, yet, just have your project use IIS instead of Cassini (the built-in web server).

Upvotes: 1

Related Questions