简体   繁体   English

根据模型中的枚举设置选中单选按钮

[英]Set Checked in Radio Button based on enum in the model

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... 我一直在玩各种方法来根据模型中的枚举在单选按钮上设置checked属性,但似乎无法正确...

@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. 很确定我错过了一些明显的东西,但我没有发现它。

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: 在html视图中编写服务器端代码的语法并不完全正确,尽管你已经足够接近了,你需要这样写:

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

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. 但是,例如在这种情况下,您需要为其添加其他语法以将“checked”或“checked ='checked'”识别为字符串。 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 此外,您可以使用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. 基本上,Razor试图将“已检查”字符串解析为服务器端命令。 And you need to tell it that it is just raw content. 你需要告诉它它只是原始内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM