如何在idictionary htmlattributes中添加属性

时间:2013-07-18 00:13:36

标签: c# asp.net-mvc razor

这里我需要在Dictionary项中添加isChecked值。

我尝试直接添加,但我收到以下错误:

 " CS1501: No overload for method 'Add' takes 1 arguments"*. Is there any alternate way to add ischecked in Idictionary.   

我的代码是:

 @{
     bool val = false;
     var isChecked = (val == true) ? new { @Checked = "checked" }  : null;
  }
@Html.RadioButtonFor(x => x.Status, "Male",new Dictionary<string,object>{{"id","GenderRdoButton"},{isChecked}})

3 个答案:

答案 0 :(得分:0)

尝试将val值传递给方法,如下所示:

@Html.RadioButtonFor(x => x.valid, val, new { @id = "GenderRdoButton" })

答案 1 :(得分:0)

您可以使用带有IDictionary的重载:

    @{
        bool val = true;
        var attributes = new Dictionary<string, string>() { {"id", "GenderRdoButton"}};
        if (val)
            attributes.Add("checked","checked");
    }
   @Html.RadioButtonFor(x => x.valid, "male", attributes) Male

答案 2 :(得分:0)

此代码对我有用,

@{
                    bool vals = false;
                    var dictionaryObj = new Dictionary<string, object>();
                    dictionaryObj.Add("id", "goodId");
                    dictionaryObj.Add("class", "sadd");
                    if(vals){
                        dictionaryObj.Add("checked", "checked");   
                    }
                }
                 @Html.RadioButtonFor(x => x.Status, "Good",dictionaryObj) Good