Question

In my MVC Project, I have a Course model looks like this:

public class Course
{
    [Key]
    public int CourseId { get; set; }

    [Required, MaxLength(50)]
    public string Name { get; set; }

   // bunch of other properties
}

I'm creating a SelectList for some Courses in my Action

var user = context.Users.Include("Courses")
          .FirstOrDefault(x => x.Email == User.Identity.Name);
var courses = user.Courses.OrderBy(x => x.Name);
ViewBag.Courses = new SelectList(courses, "CourseId", "Name");`

I have a nullable courseId parameter in my Action like this:

public ActionResult Index(int? courseId)

If it's not null, I want to change the default selected value to that course.In order to do this I tried:

if (courseId != null)
{
    var selectedCourse = courses
       .FirstOrDefault(x => x.CourseId == courseId.Value);
    if (selectedCourse != null)
    {
        ViewBag.Courses = new SelectList(courses, "CourseId", "Name", selectedCourse.CourseId);
    }
}

But it doesn't work and selectedCourse is not null.Instead of specified Course I see the first course in my list selected every time.What am I missing ?

Edit: I'm creating DropdownList in my View like this:

@Html.Bootstrap().DropDownList("Courses", (SelectList)ViewBag.Courses)
Was it helpful?

Solution

You should send the selected value via your model, but, if you want to send it via viewbag, please try like so:

@Html.DropDownListFor(model => Model.CourseId, 
   new SelectList(ViewBag.Courses, "Value", "Text", @ViewBag.CourseId))

Please see my original answer to a similar question here for more info https://stackoverflow.com/a/16799915/1477388

OTHER TIPS

If any answers solve your problem. Try it

put your selected value into a ViewBag.Seleted

$("#DropDownId option").each(function(){
   if($(this).val() == "ViewBag.Selected"){
     $(this).attr("selected","selected");
   }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top