Why does my selected value not get added to my SelectListItem as the “Text” and “Value” properties do?

56 views Asked by At

I am trying to set a default value of a list in a partial view. The partial view is called using this…

    @Html.Action("Acton", "Controller", new { department = item.Data.departmentNumber, defaultValue="someValue" })

Then in the controller I have…

  [ChildActionOnly]
    public ActionResult Categories(int? id, int? department, string defaultValue)
    {
        var typeList = from e in db.Rubrics where e.DepartmentID == department select e;
        var selectedRubrics = typeList.Select(r => r.Category);

        List<String> rubricsList = selectedRubrics.ToList();

                   var categories = new List<SelectListItem>();             
        for (int i = 0; i < rubricsList.Count(); i++)
        {
            categories.Add(new SelectListItem
            {
                Text = rubricsList[i],
                Value = rubricsList[i],
                Selected = (defaultValue == "defaultValueGetsSentToView")
            });
        }


        var ViewModel = new RubricsViewModel
        {
            Category = "Select a Category",
            Categories = categories


        };

        return View(ViewModel);





    }

Why does my selected value not get added to my SelectListItem as the “Text” and “Value” properties are? Thanks for any help!

1

There are 1 answers

4
tdbeckett On BEST ANSWER

Assuming the values in the code are the literal values you are using, "defaultValue" is "someValue" and you are setting selected with the comparison defalutValue == "defaultValueGetsSentToView".

"someValue" == "defaultValueGetsSentToView" evaluates to false.