ASP.NET MVC5 - 将项添加到模型虚拟列表

时间:2016-02-13 17:28:55

标签: asp.net-mvc asp.net-mvc-5

我有一个名为俱乐部的模型,每个俱乐部都有该俱乐部成员的虚拟列表属性。我很遗憾如何在该列表中添加更多成员,然后将其保存到我的数据库中。

public class Club
    {
        [Key]
        public int ClubID { get; set; }

        public string ClubName { get; set; }

        public string ClubDescription { get; set; }


        //List of Members that are members of this Club
        public virtual List<ClubMember> ClubMembers { get; set; }

    }//end Club

这是ClubMember模型:

public class ClubMember
{
    [Key]
    public int MemberId { get; set; }

    //First Name
    [Display(Name = "First Name")]
    public string MemberFName { get; set; }

    //Last Name
    [Required(ErrorMessage = "You must enter a Last Name")]
    [Display(Name = "Last Name")]
    public string MemberLName { get; set; }

    [Display(Name = "Member Name")]
    public string MemberName { get; set; }

    public string MemberEmail { get; set; }

    //Foreign Key for Club
    public int ClubID { get; set; }

    [ForeignKey("ClubID")]
    public virtual Club Club { get; set; }
}

我正在使用包装器模型来获取用户希望添加的成员的所选ID的列表,但我不确定是否需要这样:

public class NewMemberList //Class used when adding new members to the members list of a club
    {
        public List<ClubMember> NewMembers { get; set; }
        public List<int> SelectedIDs { get; set; }
    }

这是我目前在添加成员时的视图,它只显示一个包含成员列表和提交按钮的下拉列表

@model ultimateorganiser.Models.NewMemberList

@{
    ViewBag.Title = "Add Members";
}

@using (Html.BeginForm(@Model.SelectedIDs))
{
    @Html.AntiForgeryToken()
    @Html.ListBoxFor(m => m.SelectedIDs, new MultiSelectList(Model.NewMembers, "UserId", "UserFName", Model.SelectedIDs))

    <input type="submit" value="save" />   
}

这是我的控制器方法。它没有完成,因为我不知道如何处理帖子部分,以便它获取所选id的列表,并将该成员的所有数据添加到俱乐部的成员列表中:

 [HttpGet]
        public ActionResult AddMembers(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Club club = db.Clubs.Find(id);

            if (club == null)
            {
                return HttpNotFound();
            }

            List<ClubMember> CurrentMembers = club.ClubMembers;

            List<ClubMember> MembersList = new List<ClubMember>();
            MembersList = db.ClubMembers.ToList();

            ViewBag.CurrentMembersList = CurrentMembers;
            return View(new NewMemberList() { NewMembers = MembersList });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddMembers([Bind(Include = "SelectedIDs")] Club club)
        {
            if (ModelState.IsValid)
            {
                //Get selected members and add them to Members list for the club
                return RedirectToAction("Index");
            }
            return View(club);      

     }

如果您有任何问题或希望看到更多我的代码,请询问。

1 个答案:

答案 0 :(得分:2)

您的视图模型也应该存储ClubId,因为您要将新成员添加到特定的俱乐部。

public class AddMembersToClub
{
  public string Name { set;get;}
  public int ClubId { set;get;}
  public List<SelectListItem> Members { set;get;}
  public int[] SelectedMembers { set;get;}
}

在你的GET行动中,

public ActionResult AddMembers(int id)
{
    var club = db.Clubs.Find(id);
    if (club == null)
    {
       return HttpNotFound();
    }
  var vm = new AddMembersToClub { ClubId=id , Name = club.ClubName };
  //Here I am getting all the members, If you want a subset, update the LINQ query
  vm.Members = db.ClubMembers
              .Select(x=> new SelectListItem { Value = x.MemberId.ToString(),
                                               Text=x.MemberFName }).ToList();
  return View(vm);
}

并且在您的视图中,它是我们的AddMembersToClub视图模型的强类型。您需要将ClubId保留在HttpPost操作中我们需要的隐藏表单字段中。

@model AddMembersToClub
@using(Html.BeginForm())
{
   <p>Adding members to @Model.Name</p>

   @Html.HiddenFor(s=>s.ClubId)
   @Html.ListBoxFor(s => s.SelectedMembers, Model.Members)

   <input type="submit" />
}

在您的HttpPost操作中,读取SelectedMembers属性,该属性是一个存储所选成员的Id并使用Id的int数组,获取Member实体并udpate ClubId属性。

[HttpPost]
public ActionResult AddMembers(AddMembersToClub model)
{
   foreach(var item in model.SelectedMembers)
   {
     var member = db.ClubMembers.FirstOrDefault(s=>s.MemberId==item);
     if(member!=null)
     {
        member.ClubId = model.ClubId;
     }
     db.SaveChanges();
   }
   return ReidrectToAction("Index");
}