How to make an AJAX request using MVC 3.0 RAZOR?

I have the code below that runs when a parameter is changed in the drop-down list:

function ddlSqlList_onchange(listItemId) { $.get('/SqlReportList/SqlQuery', { "listItemId": listItemId }, function (data) { alert('succeeded'); $('#tbSqlQuery').text(data); });} 

"SqlReportList" is my controller, SqlQuery is Action, and listItemId is the input parameter for this action.

  public string SqlQuery(string listItemId) { // code here } 

It works fine, but when deployed to our dev server it doesn't work.

I realized that the URL must be changed to "/ ApplicationName / SqlReportList / SqlQuery" to make it work on the server.

So how to get the application path at runtime?

+4
source share
4 answers

What version of MVC are you using.

In MVC 3.0, with Razor, you can use:

 @Url.Action("SqlQuery","SqlReportList") 

or you can use:

 @Server.MapPath("~") 

to get the base address of your application, and then create it yourself. Server.MapPath also works in the controller if that helps. (It seems that the Url class is also available in the controller)

(from memory)

edit comment:

If you are in the .cshtml file, it will look like this:

 function ddlSqlList_onchange(listItemId) { $.get('@Url.Action("SqlQuery","SqlReportList")', { "listItemId": listItemId }, function (data) { alert('succeeded'); $('#tbSqlQuery').text(data); });} 
+3
source

If you don't want to write inline JavaScript so much, you can save the url in a hidden field like this.

 <input type="hidden" id="myGetUrl" value="@(Url.Action("ActionName", "Controller"))" /> 

Inside your javascript

 function ddlSqlList_onchange(listItemId) { var url = $('#myGetUrl').val(); $.get(url, { "listItemId": listItemId }, function (data) { alert('succeeded'); $('#tbSqlQuery').text(data); } );} 
+4
source

if you are using aspx, you are using the following:

 $.ajax({ type: 'POST', url: '<%=Url.Action("ActionName","ControllerName")%>', data: { dataNameInAction: dataValue }, success: function () { callBack Success Function }, error: function () { callbackFaileFunction } }); 

and on the Side server (Controller)

you return JsonData if you are dealing with Json,

eg.

 public ActionScript Action(DataType dataNameInAction) { .. .. return Json(new { ReturnedData = value, ReturnedData2 = value2 }); } 

I hope this helps

0
source

You can use window.location.hostname and configure the url from there.

0
source

Source: https://habr.com/ru/post/1396205/


All Articles