如何通过传递多对多表来获取表的字段

本文关键字:字段 获取 何通过 | 更新日期: 2023-09-27 18:19:56

net mvc

如果创建了我的分类项目,项目用户和用户

我想通过在下拉列表中选择来自项目的id和来自用户的id来创建一个projectUser

我的项目用户控制器

 // GET: /ProjectUser/Create
    public ActionResult Create()
    {
        ViewBag.UserID = new SelectList(db.Users, "Id", "UserName");
        ViewBag.ProjectID = new SelectList(db.Projects, "Id", "ProjectID");
        return View();
    }
    // POST: /ProjectUser/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include="ProjectUserID")] ProjectUser projectuser)
    {
        if (ModelState.IsValid)
        {
            db.ProjectUsers.Add(projectuser);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.UserID = new SelectList(db.Users, "Id", "UserName", projectuser.User.Id);
        ViewBag.ProjectID = new SelectList(db.Projects, "Id", "ProjectID", projectuser.Projects.ProjectID);
        return View(projectuser);
    }

我的观点

<div class="form-horizontal">
    <h4>ProjectUser</h4>
    <hr />
    @Html.ValidationSummary(true)
    <div class="form-group">
        @Html.LabelFor(model => model.Projects, "Kies project", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("ProjectID", String.Empty)
            @Html.ValidationMessageFor(model => model.Projects)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.User, "Kies user", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("Id", String.Empty)
            @Html.ValidationMessageFor(model => model.User)
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>

我的项目用户类

 public class ProjectUser
    {
        public int ProjectUserID { get; set; }
        public virtual ApplicationUser User { get; set; }
        public virtual Project Projects { get; set; }
    } 

如何通过传递多对多表来获取表的字段

ProjectUser类中应该有ApplicationUserId和ProjectId。然后,只需绑定id就可以简单地添加一个ProjectUser。