How to make ListBoxFor Read only in c# MVC?

I have below ListBoxFor in HTML page and I tried almost everything to make it read only but still no luck:

@Html.ListBoxFor(m => m.SelectedLocations, Model.GetLocationsNotInBuildingList(Model.idCompany, null), (edit ? extraData : new Dictionary<string, object> { { "disabled", "" } }))

I have also tried below solutions and none of them worked:

@Html.ListBoxFor(m => m.SelectedLocations, Model.GetLocationsNotInBuildingList(Model.idCompany, null), new { @readonly = "readonly" })

@Html.ListBoxFor(m => m.SelectedLocations, Model.GetLocationsNotInBuildingList(Model.idCompany, null), (edit ? extraData : new Dictionary<string, object> { { "readonly", "readonly" } }))

@Html.ListBoxFor(m => m.SelectedLocations, Model.GetLocationsNotInBuildingList(Model.idCompany, null), (edit ? extraData : new Dictionary<string, object> { { "disabled", "disabled" } }))

Any suggestions will be helpful.

Thanks.

Upvotes: 0

Views: 2187

Answers (3)

@Html.ListBoxFor(m => m.SelectedCities, Model.Cities, new {@disabled="disabled" });

It works for me. Thank you very much.

Upvotes: 0

Hiren Patel
Hiren Patel

Reputation: 135

Its working for me

@Html.ListBoxFor(m => m.SelectedCities, Model.Cities, new {@disabled="disabled" });

Upvotes: 0

Dai
Dai

Reputation: 155250

There is no readonly attribute on the <select> element in HTML because it doesn't need one: users cannot directly edit the contents of a <select> element: they can only change its selection.

If you want a listbox that users cannot change a selection for then render a normal HTML list using <ul> or <ol> and have a custom style to restrict the height and allow scrolling:

Razor:

<ul class="read-only-listbox">
@foreach(ListItem item in listItems) {
    <li>@item.Text</li>
}
</ul>

CSS:

ul.read-only-listbox {
    height: 500px;
    list-style: none;
    overflow: auto;
    border: 1px inset #ccc;
    background: white;
} 
ul.read-only-listbox li {
    display: block;
}

Upvotes: 1

Related Questions