Adam
Adam

Reputation: 17

Save radio button value to cookie and retrieve

New dev here - I have 2 radio button options as settings on my ASP.NET MVC site. I need to keep the options selected as the user navigates. These settings/values will be referenced to determine what data is loaded in razor view. After researching, I'm seeing that saving the value to a cookie is probably the best option.

What is the best approach to handle this? I've come across a few difference ideas using jquery, javascript, and C#. I can't seem to find a clean example of dealing with this in a .net app and feel lost. Any help or guidance would be great.

The options are in partial view (navbar) I imagine doing something like this to decide what 'checked' option is selected

@{
    if (Context.Request.Cookies["Instance"].Value == "1")
    {
        <form id="config">
            <div class="btn-group" id="envstatus" data-toggle="buttons">
                <label class="btn btn-default btn-on-2 btn-xs active">
                    <input type="radio" value="1" name="instance" id="PRD" checked="checked">PRD
                </label>
                <label class="btn btn-default btn-off-2 btn-xs ">
                    <input type="radio" value="0" name="instance" id="QA">QA
                </label>
            </div>
        </form>
    }
    else
    {
        <form id="config">
            <div class="btn-group" id="envstatus" data-toggle="buttons">
                <label class="btn btn-default btn-on-2 btn-xs active">
                    <input type="radio" value="1" name="instance" id="PRD">PRD
                </label>
                <label class="btn btn-default btn-off-2 btn-xs ">
                    <input type="radio" value="0" name="instance" id="QA" checked="checked">QA
                </label>
            </div>
        </form>
    }
}

Right now my action to load my partial in Home controller looks like:

 [ChildActionOnly]
        public ActionResult ConfigPanel()
        {
            return PartialView("_ConfigPanel");
        }

Thanks

Upvotes: 0

Views: 688

Answers (1)

Erfan Atp
Erfan Atp

Reputation: 393

I suggest you using the js-cookie library from the GitHub Then you can easily set and get the saved value with the simple statement.

// set
Cookies.set('radio-button', 'option-1');

// get
Cookies.get('radio-button') // => 'option-1'
Cookies.get('nothing') // => undefined

On loading the page, you should get the saved cookie value and select the related radio button as well.

Upvotes: 1

Related Questions