0

Does anyone know how to set a Yes/No radio button in MVC to a session variable in order to check the session variable later in the process. I don't want to store the value of the radio button on my model due to the fact that the user would have to edit and save, thus defaulting this user to this checkbox value.

@Html.Label("New Report")
@Html.RadioButton("requestNewReport", "1")Yes
@Html.RadioButton("requestNewReport", "0", new { @checked = "checked" })No

Thanks

devC
  • 49
  • 3
  • 9

1 Answers1

0

You can do this pretty easily with Jquery and a controller method marked with the HttpPost attribute, your controller method would look something like this:

[HttpPost]
public ActionResult GetSessionVariable()
{
    const string sessionVariableName = "MySessionVariable";

    var sessionVariable = Session[sessionVariableName] as string;

    if (sessionVariable == null)
    {
        Session[sessionVariableName] = "No";
        sessionVariable = "No";
    }

    return Content(sessionVariable);
}

Obviously your session variable would change elsewhere in your program, this just get's it as it is now, and sets it to a default value if not yet assigned.

Then in your view, you could have a form like so, containing your radio buttons, and an input button which when clicked runs a Javascript method to get the value from the above controller method without refreshing the page:

<form id="MyForm">
<fieldset>
    <legend>My Form</legend>
    <p>
        <label>Radio buttons</label>

        <input type="radio" name="radioYesNo" id="radioNo" value="No" checked="checked" />
        <label for="radioNo">No</label>

        <input type="radio" name="radioYesNo" id="radioYes" value="Yes" />
        <label for="radioYes">Yes</label>

        <button type="submit" onclick="UpdateRadioBox();">Update Radio Button</button>
    </p>
</fieldset>
</form>

The Javascript method for this update is below, it uses the ajax functionality provided by jquery to update the radio button:

<script>

    function UpdateRadioBox() {
        $("#MyForm").submit(
                function () {
                    var url = "Home/GetSessionVariable";

                    $.ajax
                    (
                        {
                            type: "POST",
                            url: url,
                            success: function (data) {
                                if (data == "Yes") {
                                    $("#radioYes").attr('checked', 'checked');
                                } else {
                                    $("#radioNo").attr('checked', 'checked');
                                }
                            }
                        }
                    );

                    return false;
                }
            );
        }

</script>

You don't have to run the Javascript under an input button, you can do this however you like (on a timer every x seconds for example).

JMK
  • 27,273
  • 52
  • 163
  • 280