0

I have an MVC 5.2.3 web project.

I have a model:

public class InstanceOnboarding : IInstanceOnboarding
{
    public int ID { get; set; }
    public int InstanceID { get; set; }
    public string InstanceName { get; set; }
    //etc...
}

And I am displaying the model with Html.EditorFor like so:

@Html.EditorFor(model => model, "InstanceOnboarding")

In Views/Shared/EditorTemplates I have my InstanceOnboarding.cshtml file that defines how EditorFor() is supposed to be mapping it:

@model Models.InstanceOnboarding

@Html.HiddenFor(model => model.ID)
@Html.HiddenFor(model => model.InstanceID)
@Html.HiddenFor(model => model.AuditFileID)
//etc...

However, when the page loads and I inspect element in Chrome, I see this:

<input ... id="ID" name="ID" type="hidden" value="240">
<input ... id="InstanceID" name="InstanceID" type="hidden" value="240">

even though 240 is the value of InstanceID, and 0 is the value of ID. I know they are because I can see them in the viewModel right before the page loads. Makes no sense!

Any idea how this is happening?

EDIT: I have experimented with setting the ID to not be 0; that doesn't make a difference.

EDIT 2: Showing controller method by request: Controller method with inspecting the value (The black areas are redacted information.)

levininja
  • 3,118
  • 5
  • 26
  • 41
  • You need to show your GET method (I assume you have a parameter named `id` and you then set the value of `InstanceID` to the value of that parameter) –  Feb 14 '17 at 22:00
  • As s side note, it should be `@Html.EditorFor(model => model)` and your `InstanceOnboarding.cshtml` EditorTemplate should be located in the `/Views/Shared/EditorTemplates` (or `/Views/YourControllerName/EditorTemplates` folder –  Feb 14 '17 at 23:11

1 Answers1

1

The issue occurs because your method has a parameter id. If you navigate to the method using ../EditOnboarding/240, the DefaultModelBinder adds id: 240 to ModelState (I assume your ShowitOnboarding() method sets the value of InstanceID to the value of id, but does not set the id value).

All the HtmlHelper methods that generate form controls first check the values in ModelState and if they exist (which in your case does for id), they use that value rather that the actual property value (the 2nd part of this answer explains the behavior).

One way to solve this is to call ModelState.Clear() before returning the view (this removes all values from ModelState and the HtmlHelper methods will then use the model property value). Another alternative is to change the method parameter to int InstanceID (and add a specific route definition for the method is you want to create a route rather than a query string)

Community
  • 1
  • 1
  • Thank you! That was it. All I did was change the controller parameter to a different name ( `InstanceID` instead of `ID` ) and that fixed it. It's also good to know there is an actual reason it's behaving this way. I wish it was documented. – levininja Feb 15 '17 at 14:53