DropDownListFor does not set selected value

前端 未结 2 350
渐次进展
渐次进展 2021-01-21 18:06

I have a view that is displaying a Drop down list using the HTML helper DropDownListFor

<%: Html.DropDownListFor(Function(model) model.Manufacturer, New Selec         


        
相关标签:
2条回答
  • 2021-01-21 18:26

    Didn't get much for answers on this so started digging into how I could fix this somewhat easily. Also in my research this seemed to be a common problem for many people with the DropDownListFor HTML Helper. I figured there had to be a way to get this working since I knew the selected value property from my ViewModel was actually getting passed to the View. So javascript and jQuery to the rescue, I ended up trying to set the selected value using the jQuery .ready function and was able to successfully get this to work. So here's my jQuery fix:

    $(document).ready(function() {
    
        $("#Manufacturer").val("<%: Model.Manufacturer %>");
    
    });
    

    For sake of making this easy to follow I used the full .ready syntax, or you can just use $(function () { 'code' });

    If you want to solve this without using jQuery you can just use basic javascript syntax as well, it'll look something like this:

    document.getElementByID("Manufacturer").Items.FindByValue("<%: Model.Manufacturer %>").Selected = true;
    

    If you using the plain javascript call make sure to call this when the page is done loading data to the dropdownlist.

    In either case all this code is doing is setting the selected value on the drop down list on the client side from the passed in Manufacturer value from the Model.

    If you have any other ways to solve this problem please let me know, but this is working for me and hopefully it'll help someone else with their problem.

    Thank,

    0 讨论(0)
  • 2021-01-21 18:46

    I've done a similar quick-fix in JQuery today to fix this behaviour too :

    $(document).ready(function() {
    $(".wrapper<%: Model.Language %> option[value=<%: Model.Language %>]").attr("selected","true");
    });
    

    Though I could share it with others if needed.

    I'd still like to see a real patch to this problem so many persons seems to have in a different way, maybe with an extension method of the already existing DropDownListFor Html.helper method.

    0 讨论(0)
提交回复
热议问题