Mvc code first style

你说的曾经没有我的故事 提交于 2019-12-11 22:42:29

问题


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 this 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?


回答1:


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" =)




回答2:


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!



来源:https://stackoverflow.com/questions/6434154/mvc-code-first-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!