Ajax call Into MVC Controller- URL Issue Ajax call Into MVC Controller- URL Issue ajax ajax

Ajax call Into MVC Controller- URL Issue


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.


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


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()); }})

;