Home ListBoxFor is case insensitive
Reply: 1

ListBoxFor is case insensitive

demo
1#
demo Published in 2017-12-04 12:17:08Z

In select I have 2 options with same text, but different case: test and TEST as example.

From server I receive only one selected item test. But on UI I see both test and TEST are selected.

var tagsList = Model.AllTags.Select(t => new SelectListItem
{
    Value = t,
    Text = t
});

<div id="tags-list-container" class="review-tags__select" style="display: none;">
    @Html.ListBoxFor(m => m.SelectedTags, tagsList, new { id = "tags-list-box" })
</div>

Is there any solution to make difference between my options ?


Firstly I thought it is caused by 3rd-party library for multiple select SumoSelect but later I've tried to use native multiple select and same thing happens - in result I have 2 selected options.


UPD:

Currently my thoughts about setting selected values using jquery, something like this:

$('#tags-list-box').val('test');

But it will be better to have this in ListBoxFor extension as for me.

Stephen Muecke
2#
Stephen Muecke Reply to 2017-12-04 21:27:00Z

Internally the ListBoxFor() method generates its own IEnumerable<SelectListItem> to set the Selected property based on the value of the property your binding to.

From the source code, you can see that the private static IEnumerable<SelectListItem> GetSelectListWithDefaultValue() compares the values using StringComparer.OrdinalIgnoreCase so a value of "test" and "TEST" both match and both options would be set with the selected="selected" attribute.

If you want to use a HtmlHelper methods to generate the correct html to account for case sensitive values, then you will need to write your extension method (use the source code as a template for your code.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.344097 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO