0

请耐心等待我是 MVC 的新手。我创建了一个名为“Book”的模型,它代表一本教科书,在我的 IdentityModel 中我添加了这个:

public class User : IUser
{

// ...

[Key]
public string Id { get; set; }

public string UserName { get; set; }

// Code First will use this to create a foreign key in book
public virtual ICollection<Book> Uploaders { get; set; }

}

这在我的 Books 表中创建了一个外键,这正是我想要的。现在在我的图书控制器中,我只想在用户点击“创建”时将图书链接到用户。这就是我卡住的地方

//
// POST: /Book/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Book book)
{
    if (ModelState.IsValid)
    {
        // Save uploader here
        // book.Uploader = User.Identity;

        db.Books.Add(book);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(book);
}
4

2 回答 2

0

The userId of the current user can be found in the claims of the User property of the Controller.

Assuming the model:

public class Book
{
    [Key]
    public int Id { get; set; }

    public virtual BookUser User { get; set; }
    [ForeignKey("User")]
    public string UserId { get; set; }
}

You can then set the UserId:

//
// POST: /Book/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize] // must be authenticated to be able to set UserId
public ActionResult Create(Book book)
{
   if (ModelState.IsValid)
   {
       UserId = ((ClaimsPrincipal)User).FindFirst(c => c.Type == ClaimTypes.NameIdentifier).Value`

       db.Books.Add(book);
       db.SaveChanges();
       return RedirectToAction("Index");
   }

   return View(book);
}
于 2013-08-25T13:59:50.200 回答
0

在您的图书模型上:

public virtual User User {get;set;}
public int UserId {get;set;}

并在您的控制器中分配它。

book.User = User;
于 2013-08-24T18:36:48.487 回答