-1

I have the following code in the controller:

public ActionResult method(int? id){
    var list;
    var project;
    if(id.HasValue){
       list = repository.FindAsync(Identity.User.Id);
       project = list.FirstOrDefault(p => p.Id == id);
       ViewBag.List = list;
       ViewBag.SelectedValue = project.Id;
    }
    return View();
}

And I have this in the view

<div>
  @Html.DropDownList("projectLists", ViewBag.list as List<SelectListItem>, new { @class = "class"})
</div>

How can I use the ViewBag.SelectedValue to render the dropdown with the project that have that id. I need a little help for this because I am new in ASP.NET MVC

naufal_chiadmi
  • 301
  • 1
  • 4
  • 14

2 Answers2

2

Make it a DropDownListFor, and have a SelectedItemID property on your model to post it to.

ozz
  • 5,098
  • 1
  • 50
  • 73
0

You need to start with a view model to represent what you want to display/edit

public class MyViewModel
{
  public int SelectedProject { get; set; }
  public SelectList ProjectList { get; set; }
}

Then in the GET method

public ActionResult method(int? id)
{
  IEnumerable<Project> projects = repository.FindAsync(Identity.User.Id);
  MyViewModel model = new MyViewModel()
  {
    SelectedProject = projects.FirstOrDefault(p => p.Id == id),
    ProjectList = new SelectList(projects, "Id", "Name")
  };
  return View(model);
}

And in the view (note if the value of SelectedProject matches one of the values of the options, then that option will be selected when the view is rendered)

@model yourAssembly.MyViewModel
@using (Html.BeginForm())
{
  @Html.DropDownListFor(m => m.SelectedProject, Model.ProjectList, "-Please select-", new { @class = "class" })
  <input type="submit" ../>
}

and the POST method

public ActionResult method(MyViewModel model)
{
  // model.SelectedProject contains the ID of the selected project
}