Ragnarsson
Ragnarsson

Reputation: 1825

jQuery.post with MVC

I have one problem with jQuery.post() syntax.

I have the controller ExampleController.cs, with an action:

public ActionResult TestPost(Guid fileId) { //do something }

and the view Example.cshtml, and here I attempt to load this action:

function foo(fileGuid) {      
    $.post("Example/TestPost?fileId=" + fileGuid, function () {
        alert("success");
    });
}

But there's no alert, I think something wrong with this syntax. Can anyone help me out. Thanks.

Upvotes: 0

Views: 208

Answers (4)

Ragnarsson
Ragnarsson

Reputation: 1825

Ok, I found this way:

$.post('@Url.Action("TestPost", "Example")', {fileId : fileGuid} , function () {
        alert("success");
    });

and it works. :)

Upvotes: 0

cardori
cardori

Reputation: 235

I think you need to add a backslash on your location:

$.post("/Example...

If that does not work, try annotating your method with a post annotation:

[HttpPost]
public ActionResult TestPost(Guid fileId) { //do something }

Edit:

It is not finding your action because you are specifying the parameter as a Guid. If you change this to a string:

 public ActionResult TestPost(string fileId)
 {
       return View();
 }

and run:

$.post('/Example/TestPost?fileId=123', function () {
  alert('here');
});

It should work

Upvotes: 0

ankur140290
ankur140290

Reputation: 640

You should also check the Networks option in the console of Chrome and see if there is any error in server side. That can also be a reason why function may have failed.

Upvotes: 1

Vivek S
Vivek S

Reputation: 5550

Try adding the following 3 callbacks and see if you get an error alert,

var jqxhr = $.post("example.php", function() {
   alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

Upvotes: 1

Related Questions