0

How do I stop the values in a ViewBag being bound to controls in MVC? The view isn't strongly typed.

I am passing in a datatable to the View using a ViewBag. This datatable is passed as value to a custom control built using extension methods on HtmlHelper.

The view has some logic which relies on the EntityID, so i pass EntityID to the view using a ViewBag.

The control builds, among other things, a hidden field with the name 'EntityID' and instead of using the value i am passing from my dataset to the html helper, it binds to the value in the ViewBag instead.

return htmlHelper.Hidden(name, value, attributes);

How do i get the HtmlHelper to use my value instead of using what is in the ViewBag?

This happens when the view is rendered.

The call to the controller of the View is made via an Ajax GET request and the view html returned is appended to a div.

The GET request sends an object to the action method. The object has a property named EntityID

Developer
  • 17,809
  • 26
  • 66
  • 92
  • That's the way the `HtmHelper`methods work - they first check for a value in `ModelState`, if not found, then `ViewData` and finally the model property. –  Feb 17 '17 at 11:38
  • @StephenMuecke I could build a hidden input control string, but i wanted to know if there is a way to prevent the `HtmlHelper` from using the ViewBag during model binding. – Developer Feb 17 '17 at 11:40
  • Can you give a bit more context - is this happening when the view is first rendered, or only if you either return the view after submitting, or if the method has a parameter which matches the name. –  Feb 17 '17 at 11:43
  • @StephenMuecke I modified the question to add more context. – Developer Feb 17 '17 at 11:46
  • Does the GET method that generates this view include a parameter named `entityID`? (need to rule out `ModelState`). –  Feb 17 '17 at 11:49
  • The GET method accepts an object. The object has a property named EntityID. – Developer Feb 17 '17 at 11:50
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/135954/discussion-between-stephen-muecke-and-lakeland-fl). –  Feb 17 '17 at 11:51
  • What about naming the ViewBag.EntityId differently.....eg vbEntityId? – AntDC Feb 17 '17 at 11:57
  • Clearing model state as suggested by @StephenMuecke fixed it. Thanks! – Developer Feb 17 '17 at 12:10
  • Yes I could @AntDC or i could also generate the hidden control myself without using the Html helper. I posted the question to get a better understanding of how model binding works in MVC. – Developer Feb 17 '17 at 12:11

1 Answers1

0

You can't restrict much about the internal workings of HTML helpers, but you could always render your own:

<input type="hidden" name="@Html.NameFor(m => m.EntityID)" value="@Model.EntityID" />
Brian Mains
  • 50,520
  • 35
  • 148
  • 257