Picflight
Picflight

Reputation: 3852

How to post data using jQuery and MVC

The data on my page is such:

var userIdCol = '3,67,78,37,87';

This collection of used Id's is obtained from a Listbox via jQuery on my page.

All I want to do is post this list of UserId's to my controller and display a success message somehere on my page. "Users have been updated."

I am not sure what the signature of my controller should look like and how I should compose the jQuery when I want to pass a list like the one above?

Also, I am wondering if I really need the Controller action has to be an ActionResult?

In the past I have done other posts like so:

$.ajax({
 type: "POST",
 url: "/Issue/" + "Index",
 dataType: "html",
 data: {
 //page: 5
 projectId: $("#ProjectList").val()
 },
 success: function(v) {
 RefreshComment(v);
 },
 error: function(v, x, w) {
 //Error
 }
});

public ActionResult Index(int? page, int? projectId)
{
 //
 return View();
}

Upvotes: 2

Views: 3088

Answers (3)

Cyril Gupta
Cyril Gupta

Reputation: 13723

I seldom use $.ajax because it needs a lot of setup. I am biased towards $.post which works very well for uncomplicated post requests.

Upvotes: 0

nikunj
nikunj

Reputation: 11

You can post and get data using jquery ajax request.You can post data using post,get and json here is full explanation and source codes check out http://my-source-codes.blogspot.com/2010/10/php-jquery-ajax-post-example.html

Upvotes: 1

JMP
JMP

Reputation: 7834

I'm doing almost exactly the same thing you're doing, here is my jQuery:

    function saveConfigItemChanges() {
        var formData = $("form:1").serialize();
        $.ajax({
            "dataType":"json",
            "type":"POST",
            "url": "/Admin/PutValidationRules",
            "data":formData,
            "success":saveConfigItemChangesCallback
        });
    }

And here is my action:

    [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult PutValidationRules(ConfigItem model)
    {
        Dao.SaveConfigItem(model);

        return Json(true);
    }

As you can see, you can return a JsonResult and it will pass the Json(true) to your success callback.

Upvotes: 3

Related Questions