I have an ASP.NET Core MVC application with a view, controller and a small JavaScript file. A JavaScript function gets called when the user clicks on an item in a listbox. The JavaScript calls a function on the controller, the controller creates a SelectedListItem list and sets the values for 'Selected', 'Value' and 'Text'. 'Selected' is set to true.
What I noticed is when the JavaScript function receives the data, everything is correct but the 'Selected' field is set to false' I am not sure how that can be. Thank you for your help!
View
<div class="form-group">
@Html.LabelFor(x => Model.SelectedBaselines, htmlAttributes: new { @class = "col-form-label" })
@Html.ListBoxFor(x => Model.SelectedBaselines, new SelectList(Model.BaselinesList, "Value", "Text"), htmlAttributes: new { @class = "form-control", id = "baselines", @multiple = true, size = "10", style = "width:200px;" })
@Html.ValidationMessageFor(x => Model.SelectedBaselines, "", new { @class = "text-danger" })
</div>
Controller
public IEnumerable<SelectListItem> GetSelectedBaselines(string meterId)
{
IQueryable<SelectListItem> baselines =
from mlookup in _dbContext.MeterBaselineLookup.AsNoTracking()
join baseline in _dbContext.MeterBaseline on mlookup.MeterBaselineId equals baseline.Id
where mlookup.MeterId == Convert.ToInt32(meterId)
orderby baseline.Id
select new SelectListItem
{
Selected = true,
Value = baseline.Id.ToString(),
Text = baseline.Name
};
return new SelectList(baselines, "Value", "Text");
}
JavaScript
$('#meters').change(function() {
var url = "/Meters/GetSelectedBaselines";
$.getJSON(url,
{ meterId: $("#meters option:selected").val() },
function(data) {
$('#baselines option').prop('selected', false); // Clear selected baselines
var len = $('#baselines option').length;
for (var i = 1; i <= len; i++) {
$("#baselines option[value=" + i + "]").attr("selected", true);
}
});
});


SelectList constructor. It's ignored when binding to a model property because internally theListBoxFor()method builds its ownIEnumerable<SelectListItem>and sets the Selected property based on the value of the property your binding to. Therefore send a value as a 4th parameter that would be a condition and based on that, you can mark your item as selected.