ASP.NET MVC和Mongodb引用

时间:2014-01-27 10:25:18

标签: c# asp.net-mvc mongodb

我的申请有问题。在我的简单博客应用程序中,我有Post和Category集合: Post.cs

public class Post 
{
    [ScaffoldColumn(false)]
    [BsonId]
    public ObjectId PostId { get; set; }

    [ScaffoldColumn(false)]
    [BsonDateTimeOptions(Kind = DateTimeKind.Local)]
    public DateTime Date { get; set; }

    [Required]
    public string Title { get; set; }

    [ScaffoldColumn(false)]
    public string Url { get; set; }

    public ObjectId CategoryId { get; set; }

    [UIHint("WYSIWYG")]
    [AllowHtml]
    public string Details { get; set; }

    [ScaffoldColumn(false)]
    public string Author { get; set; }

    [ScaffoldColumn(false)]
    public int TotalComments { get; set; }

    [ScaffoldColumn(false)]
    public IList<Comment> Comments { get; set; }
}

和category.cs

 public class Category
{
    [ScaffoldColumn(false)]
    [BsonId]
    public ObjectId CategoryId { get; set; }

    [ScaffoldColumn(true)]
    [Required]
    public string Name { get; set; }

}

PostControler:

 [HttpPost]
    public ActionResult Create(Post post)
    {

        if (ModelState.IsValid)
        {
            post.Url = post.Title.GenerateSlug();
            post.Author = User.Identity.Name;
            post.Date = DateTime.Now;
            post.CategoryId = 
            _postService.Create(post);
            return RedirectToAction("Index");
        }

        return View();
    }

当我创建新帖子时,我想从列表中选择类别并在帖子集合中保存类别的“_id”。我无意解决这个问题。任何人都可以提出一些建议来解决这个问题。

1 个答案:

答案 0 :(得分:0)

我真的不明白这里的问题,但让我们逐步完成这个步骤:

首先,您必须填写可用类别列表,因此您必须在FindAll集合上致电Category

其次,您需要将此列表传递给前端,因此您需要一个包含某种字典的视图模型类,以便您可以将其绑定到下拉列表(<select>),例如< / p>

class PostCreateViewModel
{
     Dictionary<string, string> Categories {get; set;}
     /// ...
}

[HttpGet]
public ActionResult Create()
{
  var categories = _categoryService.All();
  var vm = new PostCreateViewModel();
  vm.Categories = categories.ToDictionary(p => p.CategoryId.ToString());
  // etc.
  return View(vm);
}

第三,您的Post处理程序应验证CategoryId是否正确:

[HttpGet]
public ActionResult Create(Post post)
{
  // Make sure the given category exists. It would be better to have a 
  // PostService with a Create action that checks this internally, e.g.
  // when you add an API or a different controller creates new posts as
  // a side effect, you don't want to copy that logic.
  var category = _categoryService.SingleById(post.CategoryId);
  if(category == null)
      throw new Exception("Invalid Category!");

  // Insert your post in the DB

  // Observe the PRG pattern: Successful POSTs should always redirect:
  return Redirect("foo"); 
}

某些细节可能很棘手,例如我假设post.CategoryId将通过模型绑定器填充,但您可能必须为ObjectId编写自定义模型绑定器或使用ViewModel类使用字符串并使用ObjectId.Parse解析字符串。一般来说,我建议在任何地方使用ViewModel并使用AutoMapper之类的帮助来避免编写大量的样板复制代码。