我最近开始尝试使用ASP.net MVC (4),但是我不能完全理解我所遇到的这个问题。当你知道的时候,我相信这是很容易的。
实际上,我正在尝试在我的Index视图中执行以下操作:
所以我想我需要一个局部视图,并且我已经创建了如下(_CreateNote.cshtml):
@model QuickNotes.Models.Note
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Note</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Content)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Content)
@Html.ValidationMessageFor(model => model.Content)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
在我的原始索引视图(Index.cshtml)中,我试图呈现这个局部视图:
@model IEnumerable<QuickNotes.Models.Note>
@{
ViewBag.Title = "Personal notes";
}
<h2>Personal notes</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Content)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Content)
</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>
<div>
@Html.Partial("_CreateNote")
</div>
(使用:@Html.Partial("_CreateNote"))。这似乎不起作用,因为我得到了以下错误消息:
Line 35:
Line 36: <div>
Line 37: @Html.Partial("_CreateNote");
Line 38: </div>
Source File: c:\Dropbox\Projects\workspace .NET MVC\QuickNotes\QuickNotes\Views\Notes\Index.cshtml Line: 37
Stack Trace:
[InvalidOperationException: The model item passed into the dictionary is of type 'System.Data.Entity.DbSet`1[QuickNotes.Models.Note]', but this dictionary requires a model item of type 'QuickNotes.Models.Note'.]
System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +405487
我的NotesController看起来像这样:
public ActionResult Index()
{
var model = _db.Notes;
return View(model);
}
//
// GET: /Notes/Create
public ActionResult Create()
{
return View();
}
//
// GET: /Notes/_CreateNote - Partial view
public ViewResult _CreateNote()
{
return View("_CreateNote");
}
我认为这与索引视图使用模型的方式不同有关,就像在@模型IEnumerable中一样,但无论我如何更改它,使用RenderPartial、RenderAction、将ActionResult更改为ViewResult等,我都无法让它工作。
任何建议都将不胜感激!如果你需要更多的信息,请告诉我。如果需要的话,我很乐意完成整个项目。
发布于 2012-12-18 22:08:50
将加载部分视图的代码更改为:
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
这是因为分部视图需要一个注释,但传递的却是父视图的模型,即IEnumerable
发布于 2012-12-18 22:09:25
您传递给局部视图的模型与传递给主视图的模型相同,并且它们是不同的类型。该模型是Note
s的DbSet
,您需要传入单个Note
。
您可以通过添加一个参数来完成此操作,我猜这是因为创建表单将是一个新的Note
@Html.Partial("_CreateNote", new QuickNotes.Models.Note())
https://stackoverflow.com/questions/13934671
复制相似问题