[c#] Using partial views in ASP.net MVC 4

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:

  1. List the current items in the database of type "Note" in the Index view (that's easy)
  2. 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:\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

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.

This question is related to c# asp.net-mvc razor asp.net-mvc-4 partial-views

The answer is


Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable


You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?

Examples related to partial-views

How can I pass parameters to a partial view in mvc 4 Updating PartialView mvc 4 MVC 4 - how do I pass model data to a partial view? Using partial views in ASP.net MVC 4 How to dynamically change header based on AngularJS partial view? Getting index value on razor foreach Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine Create controller for partial view in ASP.NET MVC How can I render Partial views in asp.net mvc 3? Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction