It is possibly a mistake in my syntax, but I have been unable to set a default value for my EditorFor
in my view using ViewBag
.
I have checked that the value in the ViewBag.FirstName
is being passed through correctly, it is fine. However, the field displays with no value.
My statement is:
@Html.EditorFor(model => model.Person.FirstName, new { htmlAttributes = new { @class = "form-control" } , @Value = ViewBag.FirstName })
Any help would be greatly appreciated.
Apologies for the simplicity of my question.
To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.
The ViewBag object value will be set inside Controller and then the value of the ViewBag object will be accessed in the cshtml file (View) using Razor syntax in ASP.Net MVC Razor.
You should really just do model binding the normal way: by assigning the value of the model property. ViewBag
is unmaintainable and not strongly-typed.
If you really do need ViewBag
for some reason, just move your assignment to @Value
inside your htmlAttributes
object, like so:
@Html.EditorFor(model => model.Person.FirstName, new { htmlAttributes = new { @class = "form-control", @Value = ViewBag.FirstName } })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With