html.dropdownlist 样式,@Html.DropDownList width

问题

Q: How to set width for @Html.DropDownList (and not in css)?

@Html.DropDownList("ListId", String.Empty, new {style="width: 250px;"}) @* no go!*@

回答1:

The second argument of the DropDownList helper must be an IEnumerable. You are passing a string (an empty one to be more precise). So in order to use this helper you will have to respect its signature:

@Html.DropDownList(

"ListId",

Enumerable.Empty(),

new { style = "width: 250px;" }

)

Obviously generating an empty dropdown list is of little use. You probably have a view model (you should by the way) that you want to use to bind to:

@Html.DropDownList(

"ListId",

Model.MyList,

new { style = "width: 250px;" }

)

and of course because you have a view model you should prefer to use the DropDownListFor helper:

@Html.DropDownListFor(

x => x.ListId,

Model.MyList,

new { style = "width: 250px;" }

)

and finally to avoid cluttering your HTML with styles you should use an external CSS:

@Html.DropDownListFor(

x => x.ListId,

Model.MyList,

new { @class = "mycombo" }

)

where in your external CSS you would define the .mycombo rule:

.mycombo {

width: 250px;

}

Now you have what I consider a proper code.

回答2:

You should use the View Model approach. However the lazy way out is just to give the 2nd parameter a null.

@Html.DropDownList("ListId", null, new {style="width: 250px;"})

回答3:

@Html.DropDownListFor(model => model.Test,

new SelectList(new List(), "Id", "Name"),

null, new { @id = "ddlTest", @style="width: 250px;" })

回答4:

There is a jquery technique that allows you to set the width without having to deal with the @Html.DropDownList constructor.

$(document).ready(function () {

$("#ListId").width(300);

});

来源:https://stackoverflow.com/questions/7615321/html-dropdownlist-width


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部