Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jquery设置DropDownListFor的选定值_Javascript_Jquery_Ajax_Asp.net Mvc - Fatal编程技术网

Javascript 使用jquery设置DropDownListFor的选定值

Javascript 使用jquery设置DropDownListFor的选定值,javascript,jquery,ajax,asp.net-mvc,Javascript,Jquery,Ajax,Asp.net Mvc,我有一个国家下拉列表和一个ajax帖子。当用户输入某个ID时,这将自动触发ajax帖子。其他字段(如名称和地址)填充到该字段中。但不是国家字段的下拉列表。任何能帮忙的人都会非常感激的。我尝试了很多其他的解决方案,但都失败了 ajaxpost function getmachineinfo(serial) { $.ajax({ url: '@Url.Action("getmachine", "JuraServicing")', type: "POST",

我有一个国家下拉列表和一个ajax帖子。当用户输入某个ID时,这将自动触发ajax帖子。其他字段(如名称和地址)填充到该字段中。但不是国家字段的下拉列表。任何能帮忙的人都会非常感激的。我尝试了很多其他的解决方案,但都失败了

ajaxpost

  function getmachineinfo(serial)
{
    $.ajax({
        url: '@Url.Action("getmachine", "JuraServicing")',
        type: "POST",
        data: { "serial": serial },
        success: function (data) {
            $('#customer_name').val(data.name);
            $('#Customer_address_1').val(data.address1);
            $('#customer_address_2').val(data.address2);

            //$('#country option[value="China"]').attr("selected", "selected");
           // $("#country").val(data.country);
            $("#country").val(data.country).change();
           // $('#country').val("China").attr("selected", "selected");
            //$('#country').val(data.country).attr("selected", "selected");
            //$('select[name^="country"] option[value="Singapore"]').attr("selected", "selected");
        },
        error: function (err) {

        }
    });

}
HTMl我在选择列表中有“文本”和“值”

   @Html.DropDownListFor(model => model.country,(ViewBag.countrylist as SelectList), htmlAttributes: new { @class = " form-control col-md-3" })
添加控制器

 ViewBag.countrylist  = new SelectList(db.countryLists, "Country", "Country", "Singapore");
发现问题
因为数据库中存储的数据库列表中有一个空格,导致数据不匹配

假设您要返回的数据如下所示:

[{countryName: countryText, countryId: countryValue},...]
在成功案例中,您可以执行以下操作来填充下拉列表:

for(var v in result){
  countryDropdown.append("<option>", {value: result[v].countryId, text: result[v].countryName});
}

我想我发现了问题所在。 将国家/地区列表导入数据库期间。每个国家的正面都增加了一个空间

国家表存储为“Singapore”,用户保存的数据库为“Singapore”。 这就是数据不匹配的原因


感谢大家的帮助

您要获取的数据是什么样子的?下拉列表是否在正确的位置填充了值和文本?数据的值是多少。国家/地区?它是否匹配dropdownlist中选项的一个值?是的,它匹配并且文本和值都已就位。即使我硬编码jquery中的值也没有填充
$(“#country”)。val(data.country)
应该与
数据一样有效。country
表达式的值与SELECT元素中一个选项的
属性值相同。您的页面中有任何脚本错误吗?
countryDropdown.val("specificCountryId");