0

How do I make the date field @Html.EditorFor receive date coming from a ViewBag.

Controller

var searchDateBD = db.Sequence.ToList().Select(l => l.DateFlow).Max();
ViewBag.date = searchDateBD;

View

@Html.EditorFor(model => model.Sequence.DateFlow, 
                         ViewBag.date, 
                         new { htmlAttributes = new { @class = "form-control input-lg" } })

In this way above developed by me is not correct.

How to do so that the field receives the date coming from the viewbag of the controller

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Cyberlacs
  • 191
  • 1
  • 7

2 Answers2

2

You can overwrite the value using attribute @Value:

htmlAttributes = new { @class = "form-control input-lg", @Value = ViewBag.date }

Note that @Value is written with an uppercase letter V.

Alfred Wallace
  • 1,741
  • 1
  • 14
  • 32
  • Dreadful advice - under no circumstances should the `value` (or `name`) attribute be set when using a `HtmlHelper` method –  Aug 21 '18 at 23:04
  • @StephenMuecke, can you elaborate on that? Understand that another option is to set the value of the property in the GET method before passing the model. But why is it so terrible? – Alfred Wallace Aug 22 '18 at 02:15
  • Because the `HtmlHelper` methods correctly generate the `value` attribute using (in order), the value from `ModelState`, then the `ViewDataDictionary` and finally the actual value of the property. The whole purpose of using the `HtmlHelper` methods to to get true 2-way model binding, and there is no point using them if you are just going to override their behavior (refer also [this answer](https://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111) for more explanation of why `ModelState` values are used) –  Aug 22 '18 at 02:26
2

You don't need ViewBag here. You can set the model property in the controller action and pass the model object to view back in the line returning View like:

model.Sequence.DateFlow = db.Sequence.Select(l => l.DateFlow).Max();

return View(model);

You also do not need to materialize the result by calling ToList() and leave the Max item to be calculates on the database server.

and in your view it would be like:

@Html.EditorFor(model => model.Sequence.DateFlow, 
                         new { htmlAttributes = new { @class = "form-control input-lg" } })
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • Make sure you are not saving the entity after making the change in the controller if you don't want the change persisted, some patterns will have an automatic save on dispose of context. – Richard Hubley Aug 21 '18 at 18:40
  • This should be done on a GET action method. So Why would someone persist that ? Most cases, GET's should be idempotent. – Shyju Aug 21 '18 at 18:43