简体   繁体   中英

ASP.net MVC drop down value auto select

Is there a way to set the drop-down to a selected value on form load? This code is used in ASP.net MVC4 using knockout.js

                    <select name="iResponseSource"
                        data-bind="options: sources,
                                optionsText: 'vchParameterDesc',
                                optionsValue: 'iParameterID',
                                optionsCaption: 'Select one...',
                                value: selectedResponseSource"
                        data-val="true"
                        data-val-required="Required."
                        class="form-control">
                    </select>

The value comes from Query string property(src), something like www.mysite.com/site/?src=86643

You can use your model or the ViewBag to store a value, and print that using Razor syntax:

<select name="iResponseSource"
                    data-bind="options: sources,
                            optionsText: 'vchParameterDesc',
                            optionsValue: 'iParameterID',
                            optionsCaption: 'Select one...',
                            value: '@Model.SelectedResponseID'"
<select name="iResponseSource"
                    data-bind="options: sources,
                            optionsText: 'vchParameterDesc',
                            optionsValue: 'iParameterID',
                            optionsCaption: 'Select one...',
                            value: defaultValue"
                    data-val="true"
                    data-val-required="Required."
                    class="form-control">
                </select>

In case of javascript, in the JS file -

var defaultValue = ko.observable('');

defaultValue.subscribe(function (newValue){
    //Do validation
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM