简体   繁体   中英

Unable to set Dropdown selected value in Form Submit MVC

I am trying to bind selected option as dropdown selected value in jquery. I am doing it after binding dropdown options via json. After the form submit i am unable to select the dropdown options.

Binding Dropdown Options:

$.getJSON('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]/Home/GetLanguages', function (authors) {
                $.each(authors, function (index, author) {
                    $('#ddlLanguages').append(
                        $('<option/>')
                            .attr('value', author.LanguageKey)
                            .text(author.LanguageKey)
                    );
                });
            });

jquery to set the value

$('select[name^="Languages"] option[value='+name+']').attr("selected", "selected");

How this can be done.. can anyone help me on this?

I found a solution for this. Instead of setting the dropdown value after binding the options, we can do it while binding the options.

Here is the solution.

$.getJSON('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]/Home/GetLanguages', function (authors) {
            $.each(authors, function (index, author) {
                if ('@SelLang' == author.LanguageKey)
                {
                    $('#ddlLanguages').append(
                        $('<option/>')
                            .attr('value', author.LanguageKey).attr('selected','selected')
                            .text(author.LanguageKey)

                    );
                }
                else{
                    $('#ddlLanguages').append(
                       $('<option/>')
                           .attr('value', author.LanguageKey)
                           .text(author.LanguageKey)

                   );
                }
            });
        });

Here @SelLang is the dropdown value after submitting the form.

Couldn't you simply set the value of the select?

Something like

$('select[name^="Languages"]).val(name);

You can also get your select like this

$("[name='Languages']").val(name);

And I am assuming you get the data and when it is done you set the value. If you just execute the get for the data and immediately execute the set the data might not be loaded before you try to set the value.

Tried to add this as comment but on mobile app it only allows me 15 characters?

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