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

2

5

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.

Schmeltzer answered 25/8, 2015 at 21:51 Comment(1)
Why on earth would you do this (other than to make model binding fail). Set the value of your model property (not a ViewBagproperty)Lynnalynne
F
12

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 } })
Favouritism answered 25/8, 2015 at 22:0 Comment(2)
Hi @johnnyRose, I have used this solution, though it is binding the data and showing it in the View but on Form Post I am getting null for that property. Am I missing something?Ronna
@AjendraPrasad: You should be using model binding both ways. Don’t use ViewBag - instead set the property you’re trying to bind to. If that doesn’t work, you’ll probably need to ask a new question, since the information you provided is limited.Favouritism
T
1

I know this is an old answer and thanks to johnnyRose for the correct one. I simply wanted to add that I was still not able to get the @value passed with it and it was because of the @Value a simple matter of case v=V.. Wanted to share my ignorance in hopes of helping another. :)

Transferor answered 18/1, 2018 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.