The Light
The Light

Reputation: 27011

How to Make an AJAX Get Request using MVC 3.0 RAZOR?

I have the below code which runs when an option in the drop down list is changed:

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

"SqlReportList" is my Controller, SqlQuery is an Action and listItemId is an input parameter for that action.

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

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

I realized that the URL has to change to "/ApplicationName/SqlReportList/SqlQuery" to make it work on the server.

So how to retrieve the application path at runtime?

Upvotes: 4

Views: 8991

Answers (4)

user359135
user359135

Reputation:

Which version of MVC are you using..

In MVC 3.0 with Razor you could use:

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

or you could use:

@Server.MapPath("~")

to get the base address of your app and then build it up yourself. Server.MapPath works in the controller too if that helps.(Seems the Url class is available in the controller too)

(from memory)

edit for comment:

If you are in a .cshtml file it would look like the following:

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

Upvotes: 3

Ricardo Souza
Ricardo Souza

Reputation: 16456

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

Upvotes: 0

Tx3
Tx3

Reputation: 6916

If you don't want to write inline JavaScript that much then you could store url to 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); 
    }
);}

Upvotes: 4

Zero
Zero

Reputation: 118

if you're using ASPX, you use the following :

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

and on the serverSide ( Controller )

you return the JsonData back if you're dealing with Json,

e.g.

public ActionScript Action(DataType dataNameInAction)
{
..
..

return Json(new { ReturnedData = value, ReturnedData2 = value2 });
}

I Hope This Helps

Upvotes: 0

Related Questions