I'm new to MVC, so maybe this is a stupid question - I'm trying to get my head around strongly typed views in asp.net mvc. I'm working on version 3. If I have a project with 2 models - say Person and Department. A person must belong to a department. So I have my Department model (and I've generated my controller and CRUD interface):
public class Department
{
public int Id { get; set;}
public string DeparmentName { get; set;}
}
Then I have a Person model which references 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 generate my Controller and Views. Now, when I look into the PersonController, I have the following for the Create:
public ActionResult Create()
{
ViewBag.Department_Id = new SelectList(db.Deparments, "Id", "DepartmentName");
return View();
}
and in Person\Create.cshtml, the code to create the Department drop down is
@Html.DropDownList("Department_Id", String.Empty)
As I understand it, the DropDownList Html helper is using the ViewBag to create my drop down list. However, FirstName and LastName seem to have their input fields created without relying on the ViewBag - so in my View, I can have compile time checking on my FirstName and LastName fields because my view is strongly typed, but not on my DropDownList.
Is there a reason why the DropDownList for department not strongly typed or am I doing something wrong and there is a way to make it strongly typed?
Thanks :)
Requires typecasting for complex data type and checks for null values to avoid error. If redirection occurs, then its value becomes null. ViewData is faster than ViewBag.
To summarize, ViewBag and ViewData are used to pass the data from Controller action to View and TempData is used to pass the data from action to another action or one Controller to another Controller.
A key advantage of strong data typing is that it enforces a rigorous set of rules to ensure a certain consistency of results. Further, a compiler can quickly detect an object being sent a message to which it will not respond, preventing runtime errors.
Yes you cannot pass a Viewbag from view to controller. But you can pass them using TempData.
The reason you need a viewbag is because your Person instance, to which your view binds, does not have the data for all possible departments, only the one department it belongs to. What happens in this line:
ViewBag.Department_Id = new SelectList(db.Deparments, "Id", "DepartmentName");
Is that all Departments from the DB are added to the Select List (for your DropDown to bind to) with Id as key asn DepartmentName as value. After your view is bound to the Person, the dropdown will show the appropriate Department.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With