我试图在我的视图中从数据库中检索标记并在帖子中显示它。但我不知道我怎么能做到这一点..
这是我的控制器:
public async Task<ActionResult> Create(Book model)
{
if (ModelState.IsValid)
{
if(model.TagsListing != null)
{
Collection<Tag> postTags = new Collection<Tag>();
var s = model.TagsListing.ToString();
string[] newTags = s.Split(',');
foreach (var val in newTags)
{
Tag iTag = new Tag
{
Name = val
};
db.Tags.Add(iTag);
postTags.Add(iTag);
}
model.Tags = postTags;
}
db.Books.Add(model);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.User_ID = new SelectList(db.AspNetUsers, "Id", "Email");
ViewBag.Category_id = new SelectList(db.Categories, "Category_id", "Category_name");
return View(model);
}
以下是我的数据库的几张图片:
http://i.stack.imgur.com/hegxd.png
我只想检索与帖子相关的标签,并在帖子视图中显示它们。
答案 0 :(得分:0)
假设您有一个View模型来显示Book详细信息和标签列表
public class BookDetailVm
{
public int BookId { set;get;}
public string Name { set;get;}
public List<TagVm> Tags { set;get;}
public BookDetailVm()
{
this.Tags = new List<TagVm>();
}
}
public class TagVm
{
public int Id { set;get;}
public string Name { set;get;}
}
在您的GET操作中,阅读Book实体及其Tags集合属性,将其映射到BookDetailVm的实例并将其传递给您的视图。
public ActionResult View(int id)
{
var bookVm = new BookDetailVm();
using (var db = new YourDbContext())
{
var book = db.Books.FirstOrDefault(s=>s.Id==id);
if (book != null)
{
bookVm.BookId = book.Id;
bookVm.Name = book.Name;
if (book.Tags != null)
{
bookVm.Tags = book.Tags
.Select(b => new TagVm {Id = b.Id, Name = b.Name})
.ToList();
}
}
}
return View(bookVm);
}
您的观点强烈输入BookdDetailVm
@model BookDetailVm
<h2>@Model.Name</h2>
<h3>Tags</h3>
@foreach(var t in Model.Tags)
{
<p>@t.Id</p>
<p>@t.Name</p>
}