1

我试图从 c# 实现以下 html 代码

<select>
  <option value="volvo">Volvo</option>
  <option value="saab" selected>Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

我的主要目标是在 C# 的下面做

<option value="saab" selected>Saab</option>

到目前为止,我已经完成了以下代码

StringWriter stringwriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(stringwriter);
DataTable dt1 = BAL.setDropDown(tablename, id_col, value_col, hotel_id);
//let say selected_value is 1 
if (dt1.Rows.Count > 0)
{
    foreach (DataRow row in dt1.Rows)
    {
        writer.RenderBeginTag(HtmlTextWriterTag.Option);
        if( row[0].ToString() ==1 )
        {
             // i want to add selected on option tag here!!!
        } 
        writer.AddAttribute(HtmlTextWriterAttribute.Value, row[0].ToString());
        writer.Write(row[1].ToString());
        writer.RenderEndTag();
    }
}
4

1 回答 1

2

你可以这样写:

writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected");

它会渲染

<option value="saab" selected="selected">Saab</option>

这是浏览器可以接受的。

于 2013-12-23T08:24:40.233 回答