Search code examples
modelasp.net-mvc-5html-helperasp.net-mvc-partialview

Html Helpers giving wrong value when given a certain name


I have a very weird thing going on in my MVC application. I'm rendering a partial view into a bootstrap popup. The controller action looks like this:

[HttpGet]
    public ActionResult GetModalForm(int id)
    {
        var vm = CreateViewModel(id)
        return PartialView("MyPartialView", vm);
    }

This seems to work fine, the view model has two fields in it:

 public class MyViewModel
{
    public int id { get; set; }
    public int MemberId {get ; set;}
}

So far so good, when I put a break point in the Controller action, the id and MemberId fields are set correctly.

Now here's where things get wacky, I have the following lines in my partial view (for testing the issue):

@using ()
{
    @Html.TextBox("id", Model.id)
    @Html.TextBox("something", Model.id)
    <input type='submit'/>
}

When this renders, the 1st line gives me a text box with a value equal to the MemberId field, the 2nd line gives me a value equal to the id field. I don't really understand how these two lines can be giving me different values for the same field. What's weird is why is the second line reading the MemberId field?

Has anyone seen anything like this before, or have any ideas what might be causing it? I'm reaching my wit's end.

Thanks in advance for any help.

UPDATE:

To help explain what is happening further: If my view model properties are id=x and MemberId=y. Then the following line:

@Html.HiddenFor(m => m.id)

Will render as:

<input type="hidden" id="id" name="id" value="y"/>

Solution

  • Your action accepts a parameter id. That means there's a value in Request["id"] and that value will go into the ModelState. Whatever is in ModelState takes precedence over values set on your Model. So, your textbox bound to "id" will take the value from Request["id"].

    Two things:

    1. It's always better to use the *For helpers, since these allow you to bind to your model properties in a strongly-type way.

      @Html.TextBoxFor(m => m.id)
      
    2. Whatever action parameters you have, should not have equivalently named properties on your view model, unless they actually should be the same thing and hold the same values. In other words, if the parameter id actually corresponds to MemberId, then you should either have no id property on your model, or you should rename you action parameter to memberId.