简体   繁体   English

无法在“表单提交MVC”中设置“下拉列表”选定的值

[英]Unable to set Dropdown selected value in Form Submit MVC

I am trying to bind selected option as dropdown selected value in jquery. 我正在尝试将选定的选项绑定为jquery中的下拉选定值。 I am doing it after binding dropdown options via json. 我通过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. @SelLang是提交表单后的下拉值。

Couldn't you simply set the value of the select? 您不能简单地设置选择的值吗?

Something like 就像是

$('select[name^="Languages"]).val(name); $('选择[名^ = “语言”])VAL(名称)。

You can also get your select like this 您也可以像这样选择

$("[name='Languages']").val(name); $( “[名称= '语言']”)VAL(名称)。

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? 试图将其添加为注释,但在移动应用程序上仅允许我输入15个字符?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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