开发者

Html select dropdown list - how to choose the selected value from server code

I have a select list say of stat开发者_开发知识库es in the country, which i have in a helper to include easily in any form. (removing most options to make it brief).

I have the value of the current selection stored in the database say "CA". How would i set selected="true" to option CA before rendering the list to the user?

@helper StateSelect(string name = "State")
    {
    <select name="@name" id="@name" class="required">
        <option value="">-- Select -- </option>
        <option value="AK">Alaska</option>
        <option value="AL">Alabama</option>
        <option value="AR">Arkansas</option>
        <option value="AZ">Arizona</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>
        <option value="CT">Connecticut</option>
        <option value="VA">Virginia</option>
        <option value="VT">Vermont</option>
        <option value="WA">Washington</option>
        <option value="WV">West Virginia</option>
        <option value="WI">Wisconsin</option>
        <option value="WY">Wyoming</option>
    </select>
}


As Darin Dimitrov says, the built-in stuff would be better. However, if you do need to, I think you have a few options:

  1. Add code like this to every line:
    • <option value="CA" @(name == "CT" ? "selected=selected" : "")> Connecticut</option>
  2. Just re-add the selected item to the top of the list
    • This keeps the code cleaner, the selected option is just repeated at the top (and selected there), before the entire list
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜