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);
}
});
});
The 4th parameter is meant to store the value being selected, kindly try:
return new SelectList(baselines, "Value", "Text",baselines[0].baseline.Id);
Or just this:
return new SelectList(baselines, "Value", "Text");
Try just return below
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 baselines ;
}
Reference link for related questions:
https://stackoverflow.com/a/25714016/10201850 https://forums.asp.net/t/1382564.aspx?SelectListItem+losting+select+value+in+View+page
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.