0

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>

enter image description here

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");
}

enter image description here

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);
            }  
        });
});
3
  • There is not point setting the 4th parameter in the SelectList constructor. It's ignored when binding to a model property because internally the ListBoxFor() method builds its own IEnumerable<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. Commented Apr 4, 2019 at 16:47
  • Please do not repost your same question in different posts. I've closed your previous one as a duplicate of this one, since this one has a bit more information associated with it. In the future, edit your existing question to add information. Commented Apr 4, 2019 at 16:55
  • Chris, they are not duplicates but two completely different issues. Commented Apr 4, 2019 at 17:47

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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");

1 Comment

I removed the fourth parameter and makes no difference. (I actually added the fourth parameter just to see if it would work.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.