Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  182] [ 3]  / answers: 1 / hits: 154639  / 12 Years ago, tue, april 3, 2012, 12:00:00

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


More From » jquery

 Answers
13

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.


[#86447] Sunday, April 1, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myrap

Total Points: 407
Total Questions: 105
Total Answers: 109

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
myrap questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Wed, Jan 15, 20, 00:00, 4 Years ago
Thu, Oct 24, 19, 00:00, 5 Years ago
Thu, Oct 3, 19, 00:00, 5 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;