Didaxis
Didaxis

Reputation: 8746

Add form values via jQuery, and POST to controller method

I have a table with misc. data. Each row has a checkbox. This table is NOT in a form. I want to use jQuery to grab a value from each "checked row", add those values to a form, and then post to my controller method via a traditional POST.

I grab the values I need like this:

$('#some-button').click(function(){

    var theValues = [];

    $('#some-table tbody tr td:first-child input:checkbox').each(function(){
        if(this.checked){
            theValues.push($(this).parent().next().val());
        }
    });
    $('#some-form').val(theValues.serialize()).submit();
});

The form in the view looks like this:

@using(Html.BeginForm("TheAction", "TheController",
    FormMethod.Post, new { @id = "some-form" }))
{
    <input id="some-button" type="button" value="Do Stuff" />
}

And my controller method looks like this:

[HttpPost]
public ActionResult TheAction(IEnumerable<string> values)
{
    // Do stuff with values...

    return RedirectToAction("SomewhereElse");
}

Problem is, nothing happens. Quite literally Firebug is showing zero activity going on. The values are being grabbed properly according to running the jQuery statement (where I grab the values I want from the table rows) in the FB console.

Any ideas???

UPDATE:

As per praveen's suggestion, I've tried using a hidden form field, but the problem remains...

Added this to the form:

@Html.Hidden("values", new { @id = "the-values" })

And updated my JavaScript to this:

$('#some-button').click(function(){

    var theValues = [];

    $('#some-table tbody td td:first-child input:checkbox').each(function(){
        if(this.checked){
            theValues.push($(this).parent().next().val())
        }        
    });
    $('#the-values').val(theValues);
    $('#some-form').submit();
});

Again, the problem remains. The JS 'click' event is firing, but no POST is happening. Nothing, nadda, zip.

Upvotes: 0

Views: 671

Answers (2)

praveen
praveen

Reputation: 1

The above approach works, what ever the values you want to access you can put them in the hidden variables.

@using(Html.BeginForm("TheAction", "TheController", FormMethod.Post, new { @id = "some-form" })) {     <input id="some-button" type="button" value="Do Stuff" />
  @Html.HiddenFor................
 } 

Upvotes: 0

bobek
bobek

Reputation: 8020

Try changing your form like this:

@using(Html.BeginForm("TheAction", "TheController", FormMethod.Post, new { @id = "some-form" }))
{
    <input id="some-button" type="button" value="Do Stuff" />
}

Upvotes: 1

Related Questions