0

I have an MVC project that has a radio button. Im using a custom input so it looks a bit like this.

<input class="cb_yes" data-val="true" data-val-required="You must select" id="radio_Yes" name="RadioButton" type="radio" value="True"> <span id="radio-yes"></span>Yes</label> <input class="cb_no" data-val="true" data-val-required="You must select" id="radio_No" name="RadioButton" type="radio" value="False"> <span id="radio-no"></span>No</label> 

Notice that the name is the same.

When Yes is clicked, in the browser console I can do

$("input[name='RadioButton']").val() and it came back as True. So far so good.

I'm then doing some C# to convert this value to a c# bool.

I'm doing

IsAlreadyCustomer = Convert.ToBoolean(controllerContext.HttpContext.Request.Form["RadioButton"] == "True");

but it's coming back as false. I'm looking in the "QuickWatch" to test and doing

controllerContext.HttpContext.Request.Form["RadioButton"] == "True" but thats, no suprise, false.

I cant seem to see why it's coming back as false. I dont get why my browser says True but QuickWatch is saying false

Have I wrote it correctly? What am I doing wrong?


Update:

First, I'm declaring a bool, then I try to set the bool to true based on the value of the radio button.

bool IsAlreadyCustomer; //if null then false, else IsAlreadyCustomer = Convert.ToBoolean(controllerContext.HttpContext.Request.Form["RadioButton"] == "True");` ` 
14
  • Have you tried checking Form["RadioButton"] to see what the value is? Commented Aug 8, 2018 at 21:45
  • yea. "Form doesn't exist in the current context" Commented Aug 8, 2018 at 21:48
  • 1
    You're not setting IsAlreadyCustomer to the value of the radio button though. You're setting it to the result of comparing the value of the radio button to "True". Commented Aug 8, 2018 at 22:00
  • 5
    It would be awesome if you could provide a minimal reproducible example. Commented Aug 8, 2018 at 22:04
  • 3
    Instead of doing it all in the hardest way possible, you should (1) create and use a Model class, (2) use HTML Helpers for rendering the HTML output, and (3) use Model Binding instead of messing around with Request.Form. For examples of how to do that, see e.g. this question. Commented Aug 8, 2018 at 23:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.