I have below snippet inside my Create razor View:
@Html.EditorFor(model => model.UnitPrice)
trying to directly set UnitPrice
using statement like this:
@Model.UnitPrice = 100;
I got something like null pointer exception : Object reference not set to an instance of an object.
How can I assign constant value to a field before posting to create post method?
You need to pass the model's content like this on GET method:
You need to set the value of the property in the model before you pass the model to the view. Assuming your model is
then in the GET method
If the value is a 'default' value that applies to all instances, you can also set its value in a parameter-less constructor
Note that the reason for the
NullReferenceException
is that you have not passed a model to your view.I think you may be trying to set value after textbox get loaded you need to first pass module from action like
"return View(objModel);"
and then you set value
"@Model.UnitPrice = 100;"
on top of your view and after write
"@Html.EditorFor(model => model.UnitPrice)"
code you will get value into editor. Thanks..