0

I am facing a weird problem. I have a cshtml form:

  <label class="pre_req_questions_width">
                    @Html.RadioButton("radioGroup" + Model.ID, "1", (Model.ExpectedResponse == 1 ? true : false), new { id = "rbtnYes", style = "margin-top:0px; margin-right:10px;" })Yes</label>
                <label class="pre_req_questions_width">
                    @Html.RadioButton("radioGroup" + Model.ID, "2", !(Model.ExpectedResponse == 1 ? true : false), new { id = "rbtnNo", style = "margin-top:0px;margin-right:10px;" })No</label> 

On form submit, I am getting radio group value like this:

int radioValue =  int.Parse(fc.GetValue(controlID).AttemptedValue);

It works fine when i call it from @Html.BeginForm(), but when i try to send form collection via ajax like this:

input = $(':input')

        $.ajax({
            type: "POST",
            url: '@Url.Action("SavePrerequisiteQuestion", "Dashboard", new { id = @Model.ID })',
            data: input,
            dataType: "html",
            success: function (msg) {
             alert("fine");
            }, error: function (req, status, error) {
                    // with error   
                    alert(error);
                }
        });

It send both values like this "1,2" rather than sending just selected/submitted value.

tereško
  • 58,060
  • 25
  • 98
  • 150
Siraj Hussain
  • 874
  • 9
  • 25

3 Answers3

0

In your ajax request, you're sending all :input elements as your data:

...
data: input
...

What you probably want is to just serialize your form data, and send it with the request:

...
data: input.closest('form').serialize()
...

This is assuming you have your radio buttons in a <form> tag.

bendytree
  • 13,095
  • 11
  • 75
  • 91
0

It may not be so easy to work around this. For instance, to get a selected radio button, you can do this: jQuery get value of selected radio button

So you can't just take all inputs and get the values from them... instead, you have to have more of a selective approach, and handle different elements appropriately. Checkboxes and selects will also have a similar problem.

Community
  • 1
  • 1
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
0

You can put the @Html.Beginform back in and hijack the form submit in your jQuery

$('#formID').on('submit', function(e){
    e.preventDefault();  // Just to stop the automatic Non Ajax submission of the form

    $.post($(this).attr('action'), $(this).serialize(), function (data) {
       //do stuff on success callback
       alert("fine");
    });
});

You can inherit the action path from the Html.BeginForm itself in the path below by doing $(this).attr('action') Note: If you want to manually put the path in there you still can instead of getting it from the form Then use $(this).serialize() to just serialize the whole form like the person above me suggested

Sam North
  • 61
  • 1