简体   繁体   中英

Passing an user ID in ASP.NET MVC 4

My user class has a ICollection of Projects. Now I'm passing the user ID to the create method in the Projects controller using Action Link

@Html.ActionLink("Post a project", "Create", "Project", new{id = @Model.UserId}, new{@class="btn btn-success"})

My Question is how do I capture it and associate the project with the User. Here's my controller code for the GET and POST method.

  public ActionResult Create(int id)
            {
                ViewBag.ProjectId = new SelectList(db.ProjectDetails, "ProjectDetailId", "TargetAudience");

                ViewBag.ProjectTypeId = new SelectList(db.ProjectTypes, "ProjectTypeId", "ProjectTypeName");
                ViewBag.UserId = id;
                return View();
            }

 // POST: /Project/Create





 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Project project)
    {
        if (ModelState.IsValid)
        {
            db.Projects.Add(project);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.ProjectId = new SelectList(db.ProjectDetails, "ProjectDetailId", "TargetAudience", project.ProjectId);

        ViewBag.ProjectTypeId = new SelectList(db.ProjectTypes, "ProjectTypeId", "ProjectTypeName", project.ProjectTypeId);

        ViewBag.UserId = new SelectList(db.Users, "UserId", "UserName", project.UserId);
        return View(project);
    }

Just on the controller code, on the action you are referring the Link

 [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(string id)
{
    if (ModelState.IsValid)
    {
        db.Projects.Add(project);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.ProjectId = new SelectList(db.ProjectDetails, "ProjectDetailId", "TargetAudience", project.ProjectId);

    ViewBag.ProjectTypeId = new SelectList(db.ProjectTypes, "ProjectTypeId", "ProjectTypeName", project.ProjectTypeId);

    ViewBag.UserId = new SelectList(db.Users, "UserId", "UserName", project.UserId);
    return View(project);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM