2017-01-23 109 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