繁体   English   中英

ASP.NET MVC和Mongodb参考

[英]ASP.NET MVC and Mongodb references

我的申请有问题。 在我的简单博客应用程序中,我具有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”保存在帖子集合中。 我不知道要解决这个问题。 任何人都可以提出一些建议,以解决此问题。

我在这里不太了解这个问题,但让我们逐步介绍一下:

首先,您必须填充可用类别的列表,因此必须在Category集合上调用FindAll

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

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解析字符串。 ObjectId.Parse 通常,我建议在各处使用ViewModels并使用AutoMapper之类的帮助来避免编写大量的样板复制代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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