【发布时间】:2015-04-20 21:05:00
【问题描述】:
我创建了一个博客站点,用户可以在其中 Post 一个博客,在我使用实体框架的模型和数据库中,Posts 和 Tags 之间存在多对多关系。
在我的数据库中,我也有 PostTagMap,但是我在我的 EF 模型中没有看到它。不确定我是否需要。 PostTagMap 只包含 Post 和 Tag 的唯一标识符。
(应该注意我是从模型创建的数据库)
在我的Create Post 视图(和控制器)上,我希望用户可以选择创建标签(连同那里的帖子),以确保它们彼此被识别。但是我找不到这样做的方法。
后模型:
public partial class Post
{
public Post()
{
this.Tags = new HashSet<Tag>();
}
public int Id { get; set; }
public string BlogUserEmail { get; set; }
public int CategoryId { get; set; }
public string Title { get; set; }
public string ShortDescription { get; set; }
[AllowHtml]
public string Description { get; set; }
public string Meta { get; set; }
public string UrlSlug { get; set; }
public bool Published { get; set; }
public System.DateTime PostedOn { get; set; }
public Nullable<System.DateTime> Modified { get; set; }
public virtual BlogUser BlogUser { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Post</legend>
<div class="editor-label">
@Html.HiddenFor(model => model.BlogUserEmail, User.Identity.Name)
</div>
<div class="editor-field">
@Html.ValidationMessageFor(model => model.BlogUserEmail)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.CategoryId, "Category")
</div>
<div class="editor-field">
@Html.DropDownList("CategoryId", String.Empty)
@Html.ValidationMessageFor(model => model.CategoryId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ShortDescription)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ShortDescription)
@Html.ValidationMessageFor(model => model.ShortDescription)
</div>
<div class="editor-label">
@Html.TextAreaFor(model => model.Description)
</div>
<div class="editor-field">
@Html.ValidationMessageFor(model => model.Description)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
编辑:
我无法在Create 视图中使用EditorFor 字段来获取标签。这是因为Create 视图绑定到@Model MyBlogger.Post。
标签只显示为一个集合,如果我说:
@Html.EditorFor(model => m.Tags)
然后它在渲染时在我的视图中显示为空白。
我尝试了foreach,但没有奏效。例如在我的Create 视图中尝试此操作:
@foreach (var item in Model.Tags)
{
@Html.EditorFor(model => item.Name)
@Html.EditorFor(model => item.Description)
@Html.EditorFor(model => item.UrlSlug)
}
我收到错误:Object reference not set to an instance of an object.
【问题讨论】:
-
这里有点难以理解你在问什么;
EditorFor在这种情况下没有任何意义;我怀疑你想要的是类似于 SO 的东西,你有一个输入标签的框,然后可以动态添加标签,如果它不存在,或者如果它已经存在则关联它;如果没有一些 JavaScript,你就无法真正做到这一点。 -
是的,我正在寻找一个愚蠢的版本。我想要的只是一个文本框来为帖子添加标签。这不是一个问题,它更多的是 mvc 和实体框架的问题。多对多关系是不可能实现的。
-
并非不可能实现,只是需要更多的分析思维。为什么不在表单中将文本框绑定到可以解析的字符串,然后在服务器端进行查找?
-
基本上我认为这些答案中的大多数试图暗示的是您可能无法在客户端执行此操作,它需要在服务器端执行。
-
是的,我在这里浪费了宝贵的时间,那些试图提供帮助的人也是如此:(随时添加答案。
标签: c# sql asp.net-mvc linq