1

In my MVC4 web application I have hard coded radio button list in my view as below

<input type="radio" name="CopyrightCategory" value="NotKnown" checked>
<input type="radio" name="CopyrightCategory" value="CopyrightCategory1A">xxxxxxxx
<input type="radio" name="CopyrightCategory" value="CopyrightCategory1B">yyyyyyyy

And I get value from the model as

 @Html.LabelFor(m => m.CopyrightCategory, new { @class = "control-label" })

Based on the value of m.CopyrightCategory I need to set the item as checked e.g. if the value of m.CopyrightCategory is "CopyrightCategory1B" then we will have it like this

<input type="radio" name="CopyrightCategory" value="NotKnown">
<input type="radio" name="CopyrightCategory" value="CopyrightCategory1A">xxxxxxxx
<input type="radio" name="CopyrightCategory" value="CopyrightCategory1B" checked>
rumi
  • 3,293
  • 12
  • 68
  • 109

3 Answers3

1

Ideally you would use the Html.RadioButton helper method, but if you want to create the radio buttons manually, you can add an if-statement to determine if the radio button should be checked:

<input type="radio" name="CopyrightCategory" value="CopyrightCategory1B" @if(m.CopyrightCategory == "CopyrightCategory1B"){<text>checked</text>}>
Andy T
  • 10,223
  • 5
  • 53
  • 95
  • Looks like I am incorrect about requiring a value on the `checked` attribute: β€œThe presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.” http://stackoverflow.com/questions/12700626/what-is-the-proper-way-to-check-and-uncheck-a-checkbox-in-html5 – Andy T Nov 20 '13 at 17:29
1

make something like this:

<input 
      type="radio" 
      name="CopyrightCategory" 
      value="CopyrightCategory1B" @(Model.CopyrightCategory == "CopyrightCategory1B" ? "checked" : string.Empty) >
Dmytro Rudenko
  • 2,524
  • 2
  • 13
  • 22
0

I made a short demo here is the link. I hope this will help you solve your problem. http://jsfiddle.net/6tZgk/2/

HTML

<input id = 'check' type="radio" name="CopyrightCategory" value="NotKnown" checked>
<input id='checkA' type="radio" name="CopyrightCategory" value="CopyrightCategory1A">xxxxxxxx
<input id='checkB' type="radio" name="CopyrightCategory" value="CopyrightCategory1B">yyyyyyyy
 <span id="spanId">CopyrightCategory1B</span>

your @html.label will generate a tag attach an id and will have the same functionality as the span i add here

jQuery

if($('#spanId').text() == 'CopyrightCategory1B') { $('#checkB').attr('checked','checked'); }
else if($('#spanId').text() == 'CopyrightCategory1A') {
$('#checkA').attr('checked', 'checked');;

} else $('#check').attr('checked', 'checked');;

arnoldrob
  • 813
  • 3
  • 9
  • 15