26

I've looked at the previously-posted jQuery/MVC questions and haven't found a workable answer.

I have the following JavaScript code:

$.ajax({
    type: "POST",
    url: '@Url.Action("Search","Controller")',
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});

When calling the Url the post looks like:

NetworkError: 500 Internal Server Error - <a href="http://localhost/Web/Navigation/@Url.Action(%22Search%22,%22Chat%22)"></a> 

Why does it return it like this (the logic behind it) and what's a solution?

P.S.: Additional Information: %22 is the URL Encoding Reference for <<">> character

starball
  • 20,030
  • 7
  • 43
  • 238
Mihai Labo
  • 1,082
  • 2
  • 16
  • 40

6 Answers6

60

In order for this to work that JavaScript must be placed within a Razor view so that the line

@Url.Action("Action","Controller")

is parsed by Razor and the real value replaced.

If you don't want to move your JavaScript into your View you could look at creating a settings object in the view and then referencing that from your JavaScript file.

e.g.

var MyAppUrlSettings = {
    MyUsefulUrl : '@Url.Action("Action","Controller")'
}

and in your .js file:

$.ajax({
    type: "POST",
    url: MyAppUrlSettings.MyUsefulUrl,
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});

or alternatively look at levering the framework's built in Ajax methods within the HtmlHelpers which allow you to achieve the same without "polluting" your Views with JS code.

Asef Hossini
  • 655
  • 8
  • 11
Rob Stevenson-Leggett
  • 35,279
  • 21
  • 87
  • 141
  • Ok. I might be a pain in the bum with this question: I have a view file that I've included the code you provided.( ). How can I reference that into an external javascript: – Mihai Labo Apr 03 '12 at 07:27
  • 1
    I just add the URLs to hidden inputs then access them from the external .js file. – xr280xr Jul 17 '15 at 21:33
  • Thank you. Solved after hours of frustration. – drzounds Sep 05 '18 at 02:42
  • I like to put the `URL` inside a data attribute of the `form`. Just a cleaner approach IMHO. – cytek04 Oct 11 '22 at 23:44
12

A good way to do it without getting the view involved may be:

$.ajax({
    type: "POST",
    url: '/Controller/Search',
    data: { queryString: searchVal },
    success: function (data) {
      alert("here" + data.d.toString());
    }
});

This will try to POST to the URL:

"http://domain/Controller/Search (which is the correct URL for the action you want to use)"

thetipsyhacker
  • 1,402
  • 4
  • 18
  • 39
  • Dont forget the slash before 'Controller'. It will create an incorrect URL. byut yes, this is what I use now. – Mihai Labo Jul 11 '16 at 10:45
  • Unless you need server-side logic on the url, this is cleaner. Also, MVC will cast any stringified json in the data property to the acton's parameter as long as the shape of the json matches the shape of the c# object. – Paul Aug 14 '17 at 16:46
  • As a note, this will not work if you have to cross Area boundaries. – Spencer Sullivan Nov 22 '19 at 17:12
12

you have an type error in example of code. You forget curlybracket after success

$.ajax({
 type: "POST",
 url: '@Url.Action("Search","Controller")',
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
     alert("here" + data.d.toString());
 }
})

;

Yorgo
  • 2,668
  • 1
  • 16
  • 24
4

Starting from Rob's answer, I am currently using the following syntax.Since the question has received a lot of attention,I decided to share it with you :

var requrl = '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)';
  $.ajax({
   type: "POST",
   url: requrl,
   data: "{queryString:'" + searchVal + "'}",
   contentType: "application/json; charset=utf-8",
   dataType: "html",
   success: function (data) {
   alert("here" + data.d.toString());
   }
  });
Community
  • 1
  • 1
Mihai Labo
  • 1,082
  • 2
  • 16
  • 40
2

starting from mihai-labo's answer, why not skip declaring the requrl variable altogether and put the url generating code directly in front of "url:", like:

 $.ajax({
    type: "POST",
    url: '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)',
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});
Community
  • 1
  • 1
Mpilo Z
  • 119
  • 1
  • 7
2

Simple way to access the Url Try this Code

 $.ajax({
     type: "POST",
      url: '/Controller/Search', 
     data: "{queryString:'" + searchVal + "'}",
     contentType: "application/json; charset=utf-8",
     dataType: "html",
     success: function (data) {
     alert("here" + data.d.toString());
    });
Rehmat Ali
  • 33
  • 1
  • 8