在ASP.NET Core MVC中,要在另一个视图中创建与先前创建的作者相关联的帖子,可以按照以下步骤进行。
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
}
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public List Posts { get; set; }
}
public class BlogContext : DbContext
{
public BlogContext(DbContextOptions options) : base(options)
{
}
public DbSet Posts { get; set; }
public DbSet Authors { get; set; }
}
public class PostController : Controller
{
private readonly BlogContext _context;
public PostController(BlogContext context)
{
_context = context;
}
public IActionResult Create()
{
ViewBag.Authors = _context.Authors.ToList();
return View();
}
[HttpPost]
public IActionResult Create(Post post)
{
_context.Posts.Add(post);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
@model Post
在这个示例中,我们在帖子创建视图中使用了一个下拉列表,该下拉列表显示了所有的作者,并将选择的作者ID与帖子的AuthorId属性相关联。
这样,当用户选择一个作者并提交表单时,帖子将与所选作者相关联,并保存到数据库中。
请注意,上述示例中的代码只是一个简单示例,实际应用中可能需要进行更多的验证和错误处理。