Asp.net mvc 3 引用内置帐户用户ID作为外键分配给模型
在已经存在的问题中寻找答案之后,我仍然有点困惑我应该如何继续。我是MVC3框架的新手,所以如果我听起来像个笨蛋,我会道歉 好的,我创建了一个MVC3Internet应用程序,创建了3个新用户administrator、user1和user2。我已经创建了一个新的模型,并且可以为我的“帖子”添加、编辑和删除这些项目。我目前在我的posts表中有一个名为UserID的列。我想用当前的UsersID自动填充这个。我想我会在控制器中这样定义:Asp.net mvc 3 引用内置帐户用户ID作为外键分配给模型,asp.net-mvc-3,Asp.net Mvc 3,在已经存在的问题中寻找答案之后,我仍然有点困惑我应该如何继续。我是MVC3框架的新手,所以如果我听起来像个笨蛋,我会道歉 好的,我创建了一个MVC3Internet应用程序,创建了3个新用户administrator、user1和user2。我已经创建了一个新的模型,并且可以为我的“帖子”添加、编辑和删除这些项目。我目前在我的posts表中有一个名为UserID的列。我想用当前的UsersID自动填充这个。我想我会在控制器中这样定义: [HttpPost] public Acti
[HttpPost]
public ActionResult Create(Post post)
{
if (ModelState.IsValid)
{
public int User = System.Web.Security.Membership.GetUser(id);
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(post);
}
在模型中,这是我目前拥有的:
public class Post
{
public int PostID { get; set; }
public int UserID { get; set; }
public string PostTitle { get; set; }
public int PostType { get; set; }
public string PostBody { get; set; }
public string PostBlogTitle { get; set; }
public string PostBlogURL { get; set; }
public string PostCategory { get; set; }
public string PostSEO { get; set; }
public int PostStatus { get; set; }
}
public class PostDBContext : DbContext
{
public DbSet<Post> Posts { get; set; }
}
公共类职位
{
公共int PostID{get;set;}
public int UserID{get;set;}
公共字符串PostTitle{get;set;}
公共int PostType{get;set;}
公共字符串PostBody{get;set;}
公共字符串PostBlogTitle{get;set;}
公共字符串PostBlogURL{get;set;}
公共字符串后分类{get;set;}
公共字符串PostSEO{get;set;}
public int PostStatus{get;set;}
}
公共类PostDBContext:DbContext
{
公共DbSet Posts{get;set;}
}
我想用我在控制器中新定义的变量替换
public int UserID{get;set;}
,但不确定在何处/如何添加它。我不清楚您想要实现什么。您是否只是尝试将当前用户分配给模型,保存它,然后将其传递回视图
如果是这样,您可以这样做:
[HttpPost]
public ActionResult Create(Post post)
{
if (ModelState.IsValid)
{
// Note: I'm assuming this actually works/returns an int
public int User = System.Web.Security.Membership.GetUser(id);
post.UserID = User;
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(post);
}
在发布时,请仔细检查您的用户标识信息是否保存在viewmodel中,是否保存在数据库中?当前在我的视图中,我已手动输入用户标识,并且它确实保存了。我刚刚将这一行添加到我的代码
public int User=System.Web.Security.Membership.GetUser(id)代码>今天,我还没有测试它,因为我知道模型中有些东西需要更改。没错,我也不知道这是否有效,这正是我在另一个答案中发现的。我只想将当前用户ID分配给新添加的帖子,但不确定在哪里分配。如果System.Web.Security.Membership.GetUser(ID)
返回您需要的值,则我发布的代码将正常工作。如果您询问从何处获取ID,则情况不同。因此,您不需要更改模型中的任何内容?您的模型有一个UserID属性,在我的示例中,我将该属性的值分配给您检索的ID(post.UserID=User
)。这就是你需要做的一切。好吧,这很有意义,我的代码不起作用,所以我将其更改为Guid userGuid=(Guid)Membership.GetUser().ProviderUserKey代码>但现在我遇到一个错误,无法将类型“System.Guid”隐式转换为“int”。我是否需要将模型更改为不同的数据类型,或者可以将其类型转换为int?