4

I've been playing around with various ways to set the checked property on a Radio Button based on an enum in the model, but can't seem to get it right...

@foreach (LeadPriceAdjustmentItem state in Model.LeadPriceAdjustmentList)
{
....

<input 
    type="radio" 
    name="direction_@state.StateCode" 
    id="direction_@state.StateCode" 
    @if (state.Direction == LeadPriceAdjustmentDirection.Up) { checked } /> Up

}

On the last } I am being told:

Expected {

Pretty sure I'm missing something obvious, but I'm not spotting it.

Casey Crookston
  • 13,016
  • 24
  • 107
  • 193
  • You might see [How to set a CheckBox by default Checked in ASp.Net MVC](http://stackoverflow.com/a/16435476/2026740) – Daniel Corzo Jan 17 '17 at 19:34
  • Just bind the radio buttons to your model property using `RadioButtonFor()` and the correct button will be selected - `@Html.RadioButtonFor(m => m.yourProperty, state)` and if the value of `yourProperty` is `LeadPriceAdjustmentDirection.Up` then that radio button will be selected –  Jan 17 '17 at 20:41

3 Answers3

3

Your syntax for writing writing server side code within the html of view is not completely correct, though you are close enough, you need to write it this way:

<input 
    type="radio" 
    name="direction_@state.StateCode" 
    id="direction_@state.StateCode" 
    @(state.Direction == LeadPriceAdjustmentDirection.Up ? "checked='checked'" : "")/>
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
2
<input type="radio"
    name="direction_@state.StateCode"
    id="direction_@state.StateCode"
    @(state.Direction == LeadPriceAdjustmentDirection.Up ? "checked" : "") /> Up
Casey Crookston
  • 13,016
  • 24
  • 107
  • 193
2

Razor is not perfect. It works like you "think" it should work MOST of the time. But, such as in this case, you need to add additional syntax for it to recognize "checked" or "checked='checked'" as a string. The easiest way is

<input 
    type="radio" 
    name="direction_@state.StateCode" 
    id="direction_@state.StateCode" 
    @(state.Direction == LeadPriceAdjustmentDirection.Up ? <text>checked='checked'</text> ? "")/>

or

<input 
    type="radio" 
    name="direction_@state.StateCode" 
    id="direction_@state.StateCode" 
    @(state.Direction == LeadPriceAdjustmentDirection.Up ? <text>checked</text> ? "")/>

Additionally, you can use Html.Raw

<input 
    type="radio" 
    name="direction_@state.StateCode" 
    id="direction_@state.StateCode" 
    @(state.Direction == LeadPriceAdjustmentDirection.Up ? Html.Raw("checked='checked'"); ? "")/>

Basically, Razor is trying to parse out the "checked" string as a server-side command. And you need to tell it that it is just raw content.

d219
  • 2,707
  • 5
  • 31
  • 36
Matt Spinks
  • 6,380
  • 3
  • 28
  • 47