Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

javascript - Ajax call Into MVC Controller- URL Issue

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> 

Could someone please explain to me why does it return it like this ( the logic behind it ) and offer me a valid solution. Thanks in advance!
P.S.: Additional Information: %22 is the URL Encoding Reference for <<">> character

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...