我刚开始学习 MVC 3,我可以就实现某事的最佳方式提出一些建议。
我有一个基本场景,我可以创建一个包含一些文本和标签对象集合的博客文章。每个博客可以有多个标签,每个标签可以附加到多个博客。
public class BlogPost
{
public int ID { get; set; }
public string BlogText { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public int ID { get; set; }
public string TagText { get; set; }
public virtual ICollection<BlogPost> Blogs { get; set; }
}
这将创建 2 个模型表,其中 id 为预期的连接表。
向 BlogPost 模型的创建视图添加一个部分的最佳方法是什么,这将允许我添加、编辑和删除一组标签(如在索引视图中)?
我最初的想法是使用通过 Model.Tags 属性传递的标记对象的部分视图,但看起来 Model 属性为空。这是一个好方法还是有更好的方法?
好的,因此创建视图的操作是生成的标准操作:
// GET: /Blog/Create
public ActionResult Create()
{
return View();
}
视图代码如下:
@model MVC_ManyToManyTest.Models.BlogPost
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>BlogPost</legend>
<div class="editor-label">
@Html.LabelFor(model => model.BlogText)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.BlogText)
@Html.ValidationMessageFor(model => model.BlogText)
</div>
<div id="HolderForPartialView">
@Html.Partial("ViewUserControl1", Model.Tags);
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
创建的部分视图是:
@model IEnumerable<MVC_ManyToManyTest.Models.Tag>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
TagText
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.TagText)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
我的问题
一旦我加载部分视图,我在这一行得到空引用:
@Html.Partial("ViewUserControl1", Model.Tags);
模型对象为空