1

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.

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, I script is external hence my problems. When I look at url being requested it is localhost/home/method1 but under IIS, I am deploying to localhost/mysite so url should be localhost/mysite/home/method1. Setting virtual path to mysite/ in propject properties makes VS url same as IIS but does not fix original problem. I may just end up embedding script and call it a day.
Looks like globals is the only way to go as I will like to keep script in external file.
I think you could clean this approach up by wrapping all your logic into a JavaScript "class", and then when you instantiate it (in your page), pass in the controller URLs as options.
that is a good suggestion too. My Javascript is either using the module or prototype pattern and so I could do what you proposed. I now have it 'working' with a global defined as appUrl = "http://" + window.location.host + '/myapp and propending my resource strings with this .
0

Just change the url line to:

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

1 Comment

This syntax does not work with Javascript in an external file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.