ASP.NET MVC 3 - DropDownListFor Fails when URL Par

2019-07-02 01:43发布

问题:

I am not sure if this is a bug with the DropDownListFor extension or what, but we had the following:

http://mydomain.com/path/page?myparam=myvalue

In my View Model I have the following:

public string MyParam { get; set; }
public List<SelectListItem> ParamOptions { get; set; }

When I do the following in my View it fails to select the correct value:

@Html.DropDownListFor(x => x.MyParam, Model.ParamOptions, "Select Value")

However, when I change the parameter 'MyParam' in my view model to 'MyParam2' and update my View to use MyParam2 parameter instead, it will select the correct option item given the value of MyParam2. Before it would not when the parameter name was MyParam.

Has anyone else ran into this? Is this a bug with MVC 3 or is this a bad implementation on my part?

回答1:

What about the URL mentioned,

http://mydomain.com/path/page?myparam=myvalue

The url has a queryString with key "myparam", since the name is same as property name and When the url is invoked it will add a ModelState value against "myparam".

ModelState["myparam"] will be "myvalue".

So when the page is loaded the dropdown will select "myvalue" from drop down.



回答2:

This is a well known issue. It's not a bug, because this is by design. It's more of a design limitation.

There's nothing that can be done about it, just rename your parameter or rename the property.



回答3:

This isn't much of an answer other than to say i've experienced the same behavior in a slightly different situation.

In my case I was calling a child action from the parent action and passing in a viewmodel specific to the child action, which shared some of the same property names with the parent's ViewData. When my child action partial view was rendered, it was showing viewdata from the parent controller as opposed to what was in the viewmodel I was passing to the child action. In this situation looked like view data from the parent action was polluting my child action viewmodel when the properties both had identical names.

So it looks like the binding sometimes gets confused as to what value to bind when there are name collisions. In my case I just renamed the properties in the child viewmodel to prevent this collision, but it had me pulling my hair out figuring out why the wrong value was there.

If somebody has a real answer as to why this happens I would like to know as well. To me it comes across as a binding bug, but perhaps there is an intention here.