了解可枚举和的ViewModels [英] Understanding Enumerables and ViewModels

查看:127
本文介绍了了解可枚举和的ViewModels的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习ASP.NET MVC(C#),和我目前正在处理的ViewModels。我理解的ViewModels的目的,我可以用他们通过在屏幕上获取数据,但我具有理解与他们的关系的困难 - 我的另一个新元素 - 接口

I am trying to learn ASP.NET MVC (C#), and am currently tackling ViewModels. I understand the purpose of ViewModels, and I can get data through to the screen using them, but am having difficulties with understanding their relationship with - another new element for me - interfaces.

我想达到以下几种观点:

I want to achieve the following View:


你可以看到我有一个简单的初始插入表单添加新的工作人员,与问候下拉。在此之后,有一个编辑的第二种形式,我通过现有的工作人员进行迭代,将它们的值到相应的输入栏,在这里称呼下拉列表默认为它们的相对称呼。

You can see I have a simple initial insert form for adding a new staff member, with a dropdown for salutations. Following this, there is a second form for editing where I iterate through available staff members, placing their values into relevant input fields, where the salutation dropdown defaults to their relative salutation.

我有两个领域模型/桌, Prm_Staff Prm_Salutation ,其中我访问(打错字了,我想)通过视图模型Staff_VM:

I have two Domain Models / tables, Prm_Staff and Prm_Salutation, which I am accessing (wrong word, I think) via the 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

In the View, I refer to that 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:

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 });
        }
    }

编辑:更新,以显示最新的更改

Updated to show most recent changes

推荐答案

我想你应该考虑改变你的视图模型。还做这样的事情如下:

I think you should consider change your ViewModel. Also do something like below:

视图模型

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);
    }

查看

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

You may need to add validation for insert and update staff info

   @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" />
    }

这篇关于了解可枚举和的ViewModels的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆