如何通过传递多个表来到达表的字段

时间:2014-08-28 14:55:09

标签: c# asp.net-mvc razor ado.net-entity-data-model

net mvc

如果创建了我的clas项目,projectUser和用户

我想通过在dropdownList中选择项目中的id和用户的id来创建projectUser

我的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>

我的projectUser类

 public class ProjectUser
    {

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

1 个答案:

答案 0 :(得分:-1)

您的ProjectUser类中应该有ApplicationUserId和ProjectId。 然后你可以通过绑定id来简单地添加一个ProjectUser。