JQuery in MVC - Send form data as array with getJson

1.1k Views Asked by At

I have an MVC view which updates the elements on the page by using getJSON pointing at a method in my controller periodically and parsing the returned Json.

Method blueprint in controller:

public JsonResult GetAttendeeJson()
{

    //Code which creates the Json I need.

    return Json(result, JsonRequestBehavior.AllowGet);
}

Call from View:

function showDetects() {
            // This is the main AJAX that retrieves the data.
            $.getJSON('/Attendee/CardDetections', function (data) {

                $.each(data, function (i, country) {
                    // perform actions using data.

                });

            });
        }

It's not important to understand what I'm doing but my circumstances have changed and I have now added to my view a form containing a variable amount of checkboxes (depending on which user uses the page the number of checkboxes will be different).

Checkbox form creation:

<form onsubmit="@Url.Action("Index", "Attendee")" method="post" id="checkboxform">
@{int i = 0;}
@{foreach (string s in ViewBag.LocationNames)
{
    <div class="radio-inline">
        @s
        <input class="checkboxcontrol" onchange="this.form.submit()" type="checkbox" id="CheckBoxes" name="CheckBoxes" value="@ViewBag.LocationIds[i]">
    </div> 

    i++;
}

}

</form>

The addition of this form means I now require my controller method which returns the Json to be able to use the data of these checkboxes. The GetAttendeeJson now needs to know which checkboxes are currently checked on the form.

So I want the method blueprint to be like:

 public JsonResult GetAttendeeJson(int[] checkBoxValues)
    {

        //Code which creates the Json I need using the checkbox values.

        return Json(result, JsonRequestBehavior.AllowGet);
    }

Is it possible to do this without submitting the form? I use the submit to do something else which leads to reloading the page. I use the getJson to just update page content.

Ideally I'd just like to get the Value field of the checked checkboxes in an array and send it to the GetAttendeeJson function as a parameter when calling it.

Thanks, JK

2

There are 2 best solutions below

2
On BEST ANSWER

Lets say you have following HTML -

<input type="checkbox" name="chk" value="1" /> 1
<input type="checkbox" name="chk" value="2" /> 2
<input type="checkbox" name="chk" value="3" /> 3
<input type="checkbox" name="chk" value="4" /> 4

<input type="button" id="submit" value="Submit"/>

Then we can push the checked checkboxes to an action method using AJAX POST as shown below -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(function () {
        $("#submit").click(function () {
            var vals = [];
            $('input:checkbox[name=chk]:checked').each(function () {
                vals.push($(this).val());
            });

            $.ajax({
                url: "/Home/GetAttendeeJson",
                type: "post",
                dataType: "json",
                data: JSON.stringify({ checkBoxValues: vals }),
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                    if (result.success) {
                    }
                    else {
                    }
                }
            });
        });
    });
</script>

When we click on the button, the checked checkboxes can be obtained in following controller action -

 public JsonResult GetAttendeeJson(int[] checkBoxValues)
 {
      //Code which creates the Json I need using the checkbox values.
      return Json("true", JsonRequestBehavior.AllowGet)
 }

View renders as follows where we can check/uncheck the checkboxes -

enter image description here

Then when you put a breakpoint and debug the code, output would be as shown below -

enter image description here

1
On

Try triggering ajax call periodically. So that without submitting form you can send it to your function.