[英]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.