简体   繁体   中英

Using @Html.EditorFor to create new model

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM