开发者

Mvc code first style

开发者 https://www.devze.com 2023-03-14 08:34 出处:网络
I made a simple mvc 3 web site. It\'s working fine but the database and classes are messy because I needed to make dropdownlists and I have no idea how to implement the drowdownlists using a different

I made a simple mvc 3 web site. It's working fine but the database and classes are messy because I needed to make dropdownlists and I have no idea how to implement the drowdownlists using a different style.

Here's how things look like:

public class Departments
{
   public int ID {get; set;}
   ...
}

public class Users
{
   public int ID {get; set;}
   ...
   public Department Dept {get; set;}
   public List<Department> DeptList {get; set;}
   public string SelectedDept {get; set;}       
}

then I used DropDownListFor helper. I'm new on t开发者_JAVA技巧his code first thing, sadly. So, now I got these 2 extra unnecessary columns along in the database. Any other way to do this cleaner/better?


Your class should look like this

public class Users
{
   public int ID {get; set;}
   ...
   public virtual int DeptId {get; set;}
    [ForeignKey("DeptId")]
   public virtual Department Dept {get; set;}

}

Then in your MVC .NET Controller you perform a query to populate List DeptList. DeptList can be stored in ViewBag.DeptList or as a property of the Model you return to the view.

string SelectedDept is not needed. When you use DropDownListFor helper it will automatically set Users.DeptId for you.

Also you may want to consider renaming "Users" to "User" =)


The List should only be exposed to what's coined the ViewModel.

From what I'm reading in your post, you're binding the actual POCO object directly to the view. This is usually not in your best interests (one of the reasons being what you're seeing.) You're tightly coupling your UI models to your data entities. This isn't a situation you want to be in.

Instead of binding the POCO to the view, create an intermediary, the view model if you will, something like so.

public class SomeMethodViewModel
{
    public SomeMethodViewModel()
    {
        DepartmentList = new List<Department>();
    }

    public int Id { get; set; }
    public string SelectedDepartment { get; set; }
    public List<Department> DepartmentList { get; set;
}

Now you have a view model which is specific to your action and contains exactly the information you need. Your action now becomes something akin to:

public ActionResult SomeMethod()
{
    var vm = new SomeMethodViewModel();
    vm.DepartmentList = **Some_Method_To_Retrieve_List_Of_Departments**

    return View(vm);
}

You now have a strongly typed model to bind to the view and your POCO stays clean. When the user posts back and you've validated the data it's a matter of mapping it to your POCO entity.

Daveo's answer is correct as well. I just think the missed point is you appear to be binding directly from you POCO to the view.

Hopefully that helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号