I have recently started playing around with ASP.net MVC (4), but I can't wrap my head around this one issue I'm having. I'm sure it's easy when you know it.
I'm essentially trying to do the the following in my Index view:
- List the current items in the database of type "Note" in the Index view (that's easy)
- Creating new items in the same Index view (not so easy).
So I figured I needed a partial view, and that I have created as following (_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>
}
In my original Index view (Index.cshtml) I'm trying to render this partial view:
@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>
(using: @Html.Partial("_CreateNote"))
However. This doesn't seem to work, as I get the following error message:
Line 35:
Line 36: <div>
Line 37: @Html.Partial("_CreateNote");
Line 38: </div>
Source File: c:DropboxProjectsworkspace .NET MVCQuickNotesQuickNotesViewsNotesIndex.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
My NotesController looks like this:
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");
}
I think it has to do with the fact that the Index view is using the model differently, as in @model IEnumerable, but no matter how I change it around, using RenderPartial, RenderAction, changing ActionResult to ViewResult etc, I can't get it to work.
Any tips would be greatly appreciated!
Please let me know if you need any more information. I'd be happy to zip down the entire project if needed.
See Question&Answers more detail:
os