Johan de Klerk
Johan de Klerk

Reputation: 2535

Redirect to controller using JavaScript and MVC

Im trying to redirect to a Controller from JavaScript using this line of code

 location.href = '/Dashboard/';

It redirects to the Dashboard but on my dashboard view this method is called when the document loads

 $.post("Dashboard/UsersGet", {}, function (dataSet) {
    //do something with the dataset
 }); 

I then get this error.

POST http://localhost:1414/Dashboard/Dashboard/UsersGet 404 (Not Found) 

I can see that dashboard is added to the url twice. How can I redirect to a Controller without this happening?

Upvotes: 1

Views: 3263

Answers (3)

yourdreamer
yourdreamer

Reputation: 61

 $.post("Dashboard/UsersGet", {}, function (dataSet) {
    //do something with the dataset
 }); 

should be

 $.post("/Dashboard/UsersGet", {}, function (dataSet) {
    //do something with the dataset
 }); 

Without '/' the url which you post will be appended to the current url.

Upvotes: 0

webdeveloper
webdeveloper

Reputation: 17288

Try this:

 $.post("/Dashboard/UsersGet", {}, function (dataSet) {
    //do something with the dataset
 }); 

Add / to the url.

Upvotes: 1

gdoron
gdoron

Reputation: 150253

Use the Url helper:

@Url.Action("UsersGet", "Dashboard")

Full code:

$.post('@Url.Action("UsersGet", "Dashboard")', {}, function (dataSet) {
    //do something with the dataset
 });    

Routes in Asp .Net MVC don't work like in classic Asp.Net.

Upvotes: 2

Related Questions