Displaying the Value of a ViewBag in the EditorFor() method of a View using ASP.NET MVC

fuzzi picture fuzzi · Aug 25, 2015 · Viewed 16.8k times · Source

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.

Answer

johnnyRose picture johnnyRose · Aug 26, 2015

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 } })