views:

40

answers:

1

Is this a bug or a feature?

All code below has been simplified for the sake of brevity and easy replication and does not actually do anything useful other than highlight the behavior.

I have a class that includes an int named ID:

public class FooterLink
{
    public int ID { get; set; }
}

In my controller, I have an Edit actionresult that takes a parameter called 'id':

public ActionResult Edit(int id)
{
    return View(new FooterLink() { ID = 5 }); //notice that I am explicitly setting the ID value here.
}

in my index view I have a link to the edit action that specifies the 'id' parameter:

<%= Html.ActionLink("Edit", "Edit", new { id = 1 })%>

In my view I have a couple of text boxes:

<%= Html.TextBox("ID", Model.ID)%>
<%= Html.TextBox("Blah", Model.ID) %>

which renders the following in HTML:

<input id="ID" name="ID" type="text" value="1">
<input id="Blah" name="Blah" type="text" value="5">

Notice that the input with an id of "ID" is getting its value not from the Model like I am telling it to...but from the parameter that was supplied to my ActionResult. This behavior is the same with Html.TextBoxFor, Html.Hidden, Html.HiddenFor, etc.

What gives?

+1  A: 

That's how html helpers work. They will first look if there's ID parameter in the request url and use that value instead of the one specified as second argument in the model.

Darin Dimitrov
@Darin Indeed, that does seem to be the case. It just seems wrong to me. It is the correct behavior when you just give it a name (i.e. <%= Html.TextBox("ID")%>), but if I specify that the value should come from the model using <%= Html.TextBox("ID", Model.ID)%> or <%= Html.TextBoxFor(x => x.ID)%>, then that is where the value should come from I would think. It is especially troubling that TextBoxFor exhibits this behavior since that is supposed to be entirely model driven.
Bradley Mountford
@Bradley, I agree with you that this behavior could be misleading to someone not familiar with it but once you get used to it there should be no problems.
Darin Dimitrov