Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 607
fuzzi Avatar asked Aug 25 '15 21:08

fuzzi


People also ask

How do you show ViewBag value in view?

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.

How do I get the ViewBag value in HTML?

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.


1 Answers

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 } })
like image 55
johnnyRose Avatar answered Sep 30 '22 16:09

johnnyRose