The error your getting has nothing to do with using the HtmlHelper
methods. It occurs because your EditModal
partial has a @model Contact
declaration and you calling it using @Html.Partial()
without passing it an instance of Contact
, so by default it passes the model in the main view witch is List<Contact>
- they are not the same, hence the error. For more explanation, refer The model item passed into the dictionary is of type .. but this dictionary requires a model item of type.
The HtmlHelper
methods do not need a model because they use ModelMetadata
to generate the html attributes of the form control (and will use the models default values to generate the value
attribute if the model is null
).
You can fix the error by simply using @Html.Partial("EditModal", new Contact())
to pass a default instance of your model. From the comments, its not clear why you specifically do not want to do that (its good practice and has no measurable performance impact). But as an alternative you can use @Html.Action()
to generate the dialog/form. Create a method in your controller, say
[ChildActionOnly]
public PartialViewResult EditModal()
{
return View(); // not passing a model
}
and in the main view, use (assuming the method is in the same Controller)
@Html.Action("EditModal") // or @{ Html.RenderAction("EditModal"); }
to render the partial without passing it a model.
But its still good practice to use return view(new Contact());
so that you do pass a new instance of the model to the view (and it will save you pain later when trying to track down errors such as when someone adds say <div>@Model.SomeProperty</div>
in the partial which will throw a NullReferenceException
).