簡體   English   中英

根據模型中的枚舉設置選中單選按鈕

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

我一直在玩各種方法來根據模型中的枚舉在單選按鈕上設置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

}

在最后}我被告知:

預期{

很確定我錯過了一些明顯的東西,但我沒有發現它。

在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

剃刀並不完美。 它的工作方式就像你“認為”它應該在大部分時間都有效。 但是,例如在這種情況下,您需要為其添加其他語法以將“checked”或“checked ='checked'”識別為字符串。 最簡單的方法是

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

要么

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

此外,您可以使用Html.Raw

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

基本上,Razor試圖將“已檢查”字符串解析為服務器端命令。 你需要告訴它它只是原始內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM