ASP.NET MVC3 why dropdownlist relies on viewbag even in strongly typed form

I'm new to MVC, so maybe this is a stupid question - I'm trying to figure out strongly typed views in asp.net mvc. I am working on version 3. If I have a project with two models - say “Person” and “Department”. A person must belong to a department. So, I have a model of my department (and I created my controller and CRUD interface):

public class Department { public int Id { get; set;} public string DeparmentName { get; set;} } 

Then I have a Person model that references the Department:

 public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int Department_Id { get; set; } [ForeignKey("Department_Id") public virtual Department Department { get; set;} } 

Now I create my controller and views. Now when I look in PersonController, I have the following for Create:

 public ActionResult Create() { ViewBag.Department_Id = new SelectList(db.Deparments, "Id", "DepartmentName"); return View(); } 

and in Person \ Create.cshtml the code for creating a drop-down section is

 @Html.DropDownList("Department_Id", String.Empty) 

As I understand it, the DropDownList Html helper uses the ViewBag to create my drop-down list. However, FirstName and LastName have their own input fields created without using the ViewBag - so in my view I can check the compilation time in the FirstName and LastName fields because my view is strongly typed, but not on my DropDownList.

Is there a reason why the DropDownList for the department didn’t dial strongly or am I doing something wrong and is there a way to make it strongly typed?

Thanks:)

+6
source share
2 answers

The reason you need a view bag is because your Person instance, to which your view is attached, does not have data for all possible departments, only for one department to which it belongs. What happens on this line:

 ViewBag.Department_Id = new SelectList(db.Deparments, "Id", "DepartmentName"); 

This is what all departments from the database are added to the selection list (for your DropDown to bind) with Id as the key asn DepartmentName as the value. After your presentation is attached to the Person, the drop-down list will display the corresponding department.

+5
source

If you use strongly typed views, you must have a strongly typed model that you pass to the view:

 public class ViewData { public IList<Departments> Departments {get; set;} } 

Then in your controller you:

 public ActionResult Create() { ViewData model = new ViewData(); model.Departments = db.Deparments; return View(model); } 

The final step is to create a selection list and display it:

 @model ViewData @SelectList list = new SelectList(Model.Deparments, "Id", "DepartmentName"); @Html.DropDownList("Department_Id", list); 

Hope this makes sense.

+2
source

Source: https://habr.com/ru/post/895125/


All Articles