创建ViewModel

时间:2013-12-04 14:39:32

标签: c# asp.net-mvc-4 visual-studio-2012

我有两个表--Prm_Staff和Prm_Salutation - 其中一个包含员工姓名和一个称呼ID,另一个列出了称呼。他们的模型是这样的:

public class Prm_Staff
{
    public int ID { get; set; }
    public int SalutationID { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public bool Active { get; set; }

    //method to insert data
    public Prm_Staff(int id, int salID, string fname, string lname, bool active)
    {
        ID = id;
        SalutationID = salID;
        FName = fname;
        LName = lname;
        Active = active;
    }

    //parameterless constructor
    public Prm_Staff() { }
}

public class Prm_Salutation
{
    public int ID { get; set; }
    public string Desc { get; set; }
    public bool Active { get; set; }

    public Prm_Salutation(int id, string desc, Boolean active)
    {
        ID = id;
        Desc = desc;
        Active = active;
    }

    public Prm_Salutation() { }
}

我希望有一个

的视图
  • 插入新员工的表格,附上活动致敬的下拉列表
  • 其下方的另一个表单列出了可编辑字段中的所有当前工作人员,每个表格都有一个致敬下拉(默认值等于该行的称呼ID)。

我构建了一个满足上述要求的视图,使用linq查询通过ViewData将Salutation数据传递给视图。我想知道如何建立一个外键关系,然后如何创建一个结合了必要信息的ViewModel,并将它一次性传递给View,显然这是实现我的目标的正确方法做。

我知道我可能会变得厚颜无耻,但请在回答时使用最简单的条款。我是自学成才,你找到第二天性的术语对我来说可能是瓦肯人。还包括任何'using:...'语句,并明确 任何代码示例。

1 个答案:

答案 0 :(得分:1)

  

一个表格,用于插入新员工,并附上活动致敬的下拉列表

我会这样做。

<强>视图模型:

public class Prm_Staff_View_Model
{
    public int ID { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public bool Active { get; set; }
    //The selected One
    public int SelectedSalutationID { get; set; }
    //The list with the salutations availables
    public List<Prm_Salutation> AvailableSalutations{get;set;} 

    public Prm_Staff() { }        
}

控制器GET方法:

    // GET: /Create
    public ActionResult Create()
    {
        var staffCreateViewModel = new Prm_Staff_View_Model();
        staffCreateViewModel.AvailableSalutations = new List<Prm_Salutation>();
        //Here you get the salutations that want to display in the dropdown
        staffCreateViewModel.AvailableSalutations = context.getMySalutations();
        return View(staffCreateViewModel);
    } 

查看:使用HTML扩展程序DropDownListFor,我们可以这样做:

@Html.DropDownListFor(model => model.SelectedSalutationID, Model.AvailableSalutations.Select(option => new SelectListItem {
    Text = Html.DisplayTextFor(_ => option.Desc ).ToString(), //Text shown in the DropList
    Value = option.ID.ToString(), //Value taken
    Selected = (Model != null) && (option.ID == Model.SelectedSalutationID) //If you're gonna edit the staff member, the selected salutation is the one that already has. 
}), "Choose...")

控制器POST方式:

[HttpPost]
public ActionResult Create(Prm_Staff_View_Model viewModel)
{
   //Here you map your viewModel against the model and save it. 
   var myModel = new Prm_Staff();
   myModel.SalutationID = viewModel.SelectedSalutationID;
}

对于映射对象,我建议Nuget库AutoMapper ,或者您可以手动执行。让我知道。