Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jquery post for mvc 3 not working when deployed

So I've got this MVC 3 application that has a dropdown that I use to populate a div via jquery. It works fine locally but when I deploy it to the server it's redirecting incorrectly. Here's my jquery:

$("#ddlCategoryMain").change(function () {
    $.post("/Home/Category/", { mileID: $(this).val() }, function (data) {
        refreshDiv($("div#main"), data);
    });
});

function refreshDiv(select, data) {
    select.html("");
    select.append(data);
}

Locally this works fine. But when deployed to my server it appears to be looking for http://myserver/Home/Category instead of http://myserver/mywebsite/Home/Category

I can fix it by simply adding the name of my application before the /Home/Category in the jquery function, but that doesn't feel right...

I've also tried to add ../, ~/, ../../ before the /Home but that made no difference.

Any solutions to this minor problem? Thanks!

like image 378
LanFeusT Avatar asked Mar 09 '11 20:03

LanFeusT


Video Answer


2 Answers

Option 1

Assuming your jQuery method is in your view you can use Url.Action()

Generates a fully qualified URL to an action method by using the specified action name and controller name.

$("#ddlCategoryMain").change(function () {
    $.post('<%=Url.Action("Category", "Home")%>', { mileID: $(this).val() }, function (data) {
        refreshDiv($("#main"), data);
    });
});

Or this if you are using razor

$("#ddlCategoryMain").change(function () {
    $.post('@Url.Action("Category", "Home")', { mileID: $(this).val() }, function (data) {
        refreshDiv($("#main"), data);
    });
});

Option 2

If the method is in an external js file you could declare a global variable in your view.

var myUrl = '@Url.Action("Category", "Home")';

and then in your $.post

$("#ddlCategoryMain").change(function () {
    $.post(myUrl , { mileID: $(this).val() }, function (data) {
        refreshDiv($("#main"), data);
    });
});
like image 106
Mark Coleman Avatar answered Sep 21 '22 18:09

Mark Coleman


We were facing the same issue when we deployed the code on the server, locally it worked really fine so this helped us alot.

We are using Razor and that's what we were doing:

$.post("/Home/PostEditProduct/", { } ...

and now replaced with

$.post('@Url.Action("PostEditProduct","Home")', { } ...

and it works.

like image 44
Syed Avatar answered Sep 21 '22 18:09

Syed