2017-01-23 100 views
0

我有一個HTML類似這樣的標記:設置單選按鈕默認選擇的選項中CSHTML剃刀.NET

<input type="radio" name="shipping" value="Worldwide"> All Locations<br> 
<input type="radio" name="shipping" value="US" checked> US Only<br> 
<input type="radio" name="shipping" value="GB"> UK Only 


<input type="radio" name="type" value="all"> All Listings 
<input type="radio" name="type" value="FixedPrice" checked> Fixed Price 
<input type="radio" name="type" value="Auction"> Auction 




    <input type="radio" name="condition" value="New" checked> Brand New<br> 
       <input type="radio" name="condition" value="Used"> Used<br> 

基本上我想在這裏做的是保存用戶的喜好,然後從我的數據庫加載它們到這些複選框是這樣的:

@if (ViewBag.UserPreferences!=null) 
     { 

     @:$("input[name='shipping'][value='" + @ViewBag.UserPreferences.ShippingLocation + "']").attr('checked', 'checked'); 
     @:$("input[name='type'][value='" + @ViewBag.UserPreferences.ListingType + "']").attr('checked', 'checked'); 
     @:$("input[name='condition'][value='" + @ViewBag.UserPreferences.Condition + "']").attr('checked', 'checked'); 


     } 

的`ViewBag.UserPreferences正好等於,美在其中任何一個標籤在那裏的價值屬性看值內容。

我在做什麼錯在這裏?

+1

你應該把這個使用** $(文件)。就緒**事件 – Fals

+0

@Fals它在的document.ready已經 – User987

+1

爲什麼在世界上你不是使用'@ Html.RadioButtonFor()'方法來生成單選按鈕(它將根據你綁定的屬性的值正確選擇按鈕,並使用較少的代碼給你驗證等,沒有一個你會得到你的當前代碼 –

回答

1

您不應該爲了添加剃鬚刀值而從單引號中跳過。試試這個:

@:$("input[name='shipping'][value='@ViewBag.UserPreferences.ShippingLocation']").attr('checked', 'checked'); 

而且我也有運氣<text>

<text>$("input[name='shipping'][value='@ViewBag.UserPreferences.ShippingLocation']").attr('checked', 'checked');</text> 
+0

謝謝,作品相當好,我不能相信我忘了''! – User987