0

I have renderad a CRUD with .net and have the following files in the same folder.

Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, Index.cshtml

Now it is a link to create a new record on the index page

@Html.ActionLink("Create New", "Create")

But I want the create form to be on the index page.

I tested to use PartialView (I do not know whether it is better to copy the code from create.cshtml in index.cshtml or to use two files but I get the same error).

Changed the return in the controller to return PartialView(board);

And the view to @Html.Partial("Create")

But I get the compiling error

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Klotterplank.Models.Board]', but this dictionary requires a model item of type 'Klotterplank.Models.Board'.

This is the model I use in index.cshtml

@model IEnumerable<Klotterplank.Models.Board>

And this is the model I use in create.cshtml

@model Klotterplank.Models.Board
Md. Ilyas Hasan Mamun
  • 1,848
  • 2
  • 24
  • 15
Xtreme
  • 1,601
  • 7
  • 27
  • 59
  • You need a view model with properties for each property of `Board` that your editing, plus a collection property for the existing `Board` - refer [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Oct 05 '16 at 09:25
  • 1
    Maybe you can try to use this partial [overload](https://msdn.microsoft.com/en-us/library/system.web.mvc.html.partialextensions.partial(v=vs.118).aspx#M:System.Web.Mvc.Html.PartialExtensions.Partial%28System.Web.Mvc.HtmlHelper,System.String,System.Object%29) and pass the `Board` instance accordingly. – hendryanw Oct 05 '16 at 09:25
  • The problem with using a partial is that it will cause problems if you submit and you need to return the view because `ModelState` is invalid –  Oct 05 '16 at 09:51

2 Answers2

0

If you use a PartialView in a parent page with a different Model, you have to pass a different model to the Html Helper like this:

@Html.Partial("Create", new Klotterplank.Models.Board())
0

The error tells pretty much itself: When a partial view is instantiated, it gets a copy of the parent view’s ViewData dictionary. Your Create view needs data of different type, so you can provide it like this:

@Html.Partial("Create", viewModel)

viewModel can be equal to Model.Fist() (since on your Index view you have a collection of boards as model) for example.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132