0
votes

I want to render a form used to create a new instance of a Model. I tried,

@Html.EditorFor(model => new Person())

But I got the error,

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

I tried,

@Html.EditorForModel("MyNamespace.Person")

but nothing rendered. How do I use Html.EditorFor when I dont have a model instance to pass to it?

1

1 Answers

1
votes

It seems that you're a bit confused about how to use @Html.EditorFor(). First,, your use of the lambda expression doesn't quite make sense, model => new Person(). If you want to create a new instance of a model then there's no need to use a lambda, just new Person() gives you that instance.

Second, you don't need an actual instance to pass into @Html.EditorFor(). The purpose of this method is to produce an html markup including an input field for a property or even multiple properties.

So let's say your Person model had an Age property, then you can create an edit field for that attribute by calling

@Html.EditorFor(model => model.Age)

Now where does model come from? You have to define it in your view, so add this line to the top of your view file so that ASP.net knows which model to grab the Age attribute from,

@model <namespace>.Models.Person

The namespace is usually the name of your project, and if you don't put your models in the Models folder, then replace that with where ever your model is contained in.