了解Enumerables和ViewModels

时间:2013-12-11 12:26:30

标签: c# asp.net-mvc mvvm

我正在尝试学习ASP.NET MVC(C#),目前正在处理ViewModels。我理解ViewModels的目的,我可以使用它们将数据传递到屏幕,但是我很难理解它们与我的关系 - 另一个新的元素 - 接口。

我想实现以下观点:

example layout 您可以看到我有一个简单的初始插入表单,用于添加新的工作人员成员,以及致敬的下拉列表。在此之后,还有第二种编辑形式,我在其中迭代可用的工作人员,将其值放入相关的输入字段,其中称呼下拉列表默认为相对称呼。

我有两个域模型/表Prm_StaffPrm_Salutation,我通过ViewModel Staff_VM访问(我认为错误的词):

public class Staff_VM
{
    public int StaffID { get; set; }
    public int SalutationID { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public bool Active { get; set; }

    public List<Prm_Salutation> AvailableSalutations { get; set; }
}

public class StaffMembers
{
    public Staff_VM StaffVm;
    public IEnumerable<Staff_VM> ListStaffVms;
}

在我的控制器中:

var activeSalts = (from a in db.Prm_Salutations
                where a.Active == true
                orderby a.Desc ascending
                select a).ToList();

var model = new StaffMembers
{
    ListStaffVms = (from a in db.Prm_Staffs
                    where a.Active == true
                    orderby a.LName ascending
                    select new Staff_VM
                    {
                        StaffID = a.Prm_StaffID,
                        SalutationID = a.SalutationID,
                        FName = a.FName,
                        LName = a.LName,
                        Active = a.Active,
                        AvailableSalutations = activeSalts
                    }),
    StaffVm = new Staff_VM()
    {
        AvailableSalutations = activeSalts
    },
};

return View("StaffMembers", model);

在视图中,我引用该模型@model November.ViewModels.StaffMembers

@*Record New Staff Member*@
<tr>
<td>
    @Html.DropDownListFor(
                model => model.StaffVm.SalutationID,  
                Model.StaffVm.AvailableSalutations.Select(option => new SelectListItem
                {
                    Text = option.Desc.ToString(),
                    Value = option.Prm_SalutationID.ToString()
                }
        ),
        "Choose...")
</td>
<td>@Html.EditorFor(model => model.StaffVm.FName)</td>
<td>@Html.EditorFor(model => model.StaffVm.LName)</td>
<td>@Html.EditorFor(model => model.StaffVm.Active)</td>
</tr>

@*Update Existing Staff Members*@
@foreach (var staff in Model.ListStaffVms)
{
    <tr>
        <td>@Html.HiddenFor(model => staff.StaffID)@Html.ValueFor(model => staff.StaffID)  </td>
        <td>
            @Html.DropDownListFor(
                model => staff.SalutationID, staff.AvailableSalutations.Select(option => new SelectListItem
                    {
                        Selected = (option.Prm_SalutationID == staff.SalutationID),
                        Text = option.Desc.ToString(),
                        Value = option.Prm_SalutationID.ToString()
                    }
            ),
            "Choose...")
        </td>
        <td>@Html.EditorFor(model => staff.FName)</td>
        <td>@Html.EditorFor(model => staff.LName)</td>
        <td>@Html.EditorFor(model => staff.Active)</td>
        <td><a href="/Settings/DeleteStaff?id=@Html.ValueFor(model => staff.StaffID)">Delete</a></td>
    </tr>
}

的ActionResult:

    public ActionResult UpdateStaff(StaffMembers list)
    {
        if (ModelState.IsValid)
        {
            foreach (var staffVm in list.ListStaffVms)
            {
                Prm_Staff staff = db.Prm_Staffs.Find(staffVm.StaffID);

                staff.SalutationID = staffVm.SalutationID;
                staff.FName = staffVm.FName;
                staff.LName = staffVm.LName;
                staff.Active = staffVm.Active;
            }
            db.SaveChanges();
            ViewBag.rtrn = "Successfully Updated.";
            return RedirectToAction("Parameters", new { param = "Staff Members", rtrn = ViewBag.rtrn });
        }
        else
        {
            ViewBag.rtrn = "Failed ! Please try again.";
            return RedirectToAction("Parameters", new { param = "Staff Members", rtrn = ViewBag.rtrn });
        }
    }

编辑:已更新以显示最近的更改

1 个答案:

答案 0 :(得分:1)

我认为你应该考虑改变你的ViewModel。也做如下的事情:

<强>视图模型

public class Staff_VM
{
    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; }
}
public class MyViewModel
{
    public Staff_VM StaffVm { get; set; } 
    public List<Staff_VM> ListStaffVms { get; set; }
    public List<Prm_Salutation> AvailableSalutations { get; set; }
}

Add_Update_Staff操作

     [HttpGet]
    public ActionResult Add_Update_Staff()
     {
        var model = new MyViewModel
        {
            ListStaffVms = (from a in db.Prm_Staffs
                            where a.Active == true
                            orderby a.LName ascending
                            select new Staff_VM
                            {
                                ID = a.Id,
                                SalutationID = a.SalutationID,
                                FName = a.FName,
                                LName = a.LName,
                                Active = a.Active
                            }),
           AvailableSalutations = (from p in db.Prm_Salutations
                                    where a.Active == true
                                   orderby p.Desc ascending
                                   select p).ToList()
        };
        return View(model);
    }

更新员工职位

    [HttpPost]
    public ActionResult Add_Update_Staff(MyViewModel model, string buttonType)
    {
        if (buttonType == "Insert")
        {
            if (ModelState.IsValid)
            {
                //save a new staff info
                return RedirectToAction("Index", "Home");
            }
        }
        if (buttonType == "Update")
        {
            foreach (var staffVm in model.ListStaffVms)
            {
                // update each record here
            }
            return RedirectToAction("Index", "Home");
        }
        model.AvailableSalutations = (from p in db.Prm_Salutations
                                      orderby p.Desc ascending
                                      select p).ToList();
        return View(model);
    }

查看

您可能需要为插入和更新员工信息添加验证

   @using (Html.BeginForm("Add_Update_Staff", "Staff"))
    {
        <tr>
            <td>
                @Html.DropDownListFor(
                    model => model.StaffVm.SalutationID, Model.AvailableSalutations.Select(option => new SelectListItem
                    {
                        Text = option.Desc.ToString(),
                        Value = option.Prm_SalutationID.ToString()
                    }
                        ), "Choose...")
            </td>
            <td>@Html.EditorFor(model => model.StaffVm.FName)</td>
            <td>@Html.EditorFor(model => model.StaffVm.LName)</td>
            <td>@Html.EditorFor(model => model.StaffVm.Active)</td>
        </tr>
        <input type="submit" value="Insert" name="buttonType" />

        for (int i = 0; i < Model.ListStaffVms.Count(); i++)
        {

            <tr>
                <td>@Html.HiddenFor(m => m.ListStaffVms[i].ID)@Html.ValueFor(m => m.ListStaffVms[i].ID)  </td>
                <td>
                    @Html.DropDownListFor(
                      m => m.ListStaffVms[i].SalutationID, Model.AvailableSalutations.Select(option => new SelectListItem
                        {
                            Selected = (option.Prm_SalutationID == Model.ListStaffVms[i].SalutationID),
                            Text = option.Desc.ToString(),
                            Value = option.Prm_SalutationID.ToString()
                        }), "Choose...")
                </td>
                <td>@Html.EditorFor(model => model.ListStaffVms[i].FName)</td>
                <td>@Html.EditorFor(model => model.ListStaffVms[i].LName)</td>
                <td>@Html.EditorFor(model => model.ListStaffVms[i].Active)</td>
                <td><a href="/Settings/DeleteStaff?id=@Html.ValueFor(model => model.ListStaffVms[i].ID)">Delete</a></td>
                <hr />
            </tr>
        }
       <input type="submit" value="Update" name="buttonType" />
    }