0

I've encountered what seems to be a strange inconsistency in the values of properties in my model.

I have the following controller action...

<Route("news/edit")>
<HttpGet>
Function EditIndex(Optional filter As Models.NewsFilter = Nothing) As ActionResult
   filter.Start = 0
   filter.Count = 100

   Return View("EditIndex", filter)
End Function

Most of the properties in the model come from the querystring, but my controller explicitly setting "Start" and "Count", and then passing the model to the view.

My view is declared like so...

@inherits System.Web.Mvc.WebViewPage(Of Models.NewsFilter)

The odd thing is that if I simply display the models properties within the view like...

Start=@Model.Start
Count=@Model.Count

They display the values as defined in my controller. However when I use the following...

@Html.EditorFor(Function(m) m.Start, New With {.class = "form-control"})
@Html.EditorFor(Function(m) m.Count, New With {.class = "form-control"})

The values displayed are the original values from the QueryString. It's ignoring the values that I've set in my controller.

I don't understand why this happens. Is it trying to be clever and automatically checking the QueryString parameters because it's within a form?

user1751825
  • 4,029
  • 1
  • 28
  • 58
  • A GET method should not have a model as a parameter. The values are added to `ModelState` and the `HtmlHelper` methods for generating form controls use `ModelState` values if they exist rather that model property values. Refer [this answer](http://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111) for an explanation –  Apr 07 '16 at 08:31
  • @StephenMuecke Thanks, I think that makes sense. It seems I'm probably just doing my views incorrectly. In my case, I also need to use the values from the model to make some web-api calls from jquery, and to generate a list of results in a partial view. Anyway, at least now I understand why it's doing what it's doing, so I'll try to figure out a more standard way to achieve what I need to do. – user1751825 Apr 07 '16 at 08:47
  • Its not you view that's the problem (what you have shown is correct), its the fact you have a model as a parameter in the GET method. Remove it and if you want to pass some parameter, add those to the method and inside the function, initialize a new instance of your model and set its properties based on the parameters. –  Apr 07 '16 at 08:51
  • @StephenMuecke So I guess I should have only primitive types for the method parameters, and then use them to pre-define the model I've instantiated to pass to the view. I guess that will work. I just need to adjust my thinking a bit. Thanks for your help :-) – user1751825 Apr 07 '16 at 08:58

0 Answers0