【问题标题】:How to automatically select value from drop down list in asp.net core mvc using jquery or javascript?如何使用 jquery 或 javascript 从 asp.net core mvc 的下拉列表中自动选择值?
【发布时间】:2022-01-26 07:27:49
【问题描述】:

这里的方法不起作用。

这是我的cshtml:

<div class="form-group col-md-4">
  <label for="inputState">City</label>
  <select id="City" class="form-control basic" asp-for="City" 
    asp-items="@(new SelectList(ViewBag.Cities," Id","ZoneName"))"
    readonly="@(Model.IsView ? true : false)">
    <option value="0" selected>Select</option>
  </select>
</div>

jQuery

$("#CustomerName").change(function () {
  var CustomerName = $("#CustomerName").val();
  $.ajax({
    url: "../Ticket/FetchCustomerAddress",
    data: { userId: CustomerName },
    type: "Get",
    success: function (data) {
      alert(data.city);
      //debugger;
      $('#City').val(data.city);
    },
    error: function (err) {
      //console.error(err)
      //alert("Internal server error.");
    }
  })
});

我正在用城市填充列表。我想自动选择从data.city获取的列表中的城市

【问题讨论】:

  • 嗨@Sharad Kulshrestha。你能分享你的模型设计吗?此外,我看到你使用alert(data.city);, 它会提醒正确的值吗?另外,如果可能,请分享您的FetchCustomerAddress 返回数据。

标签: javascript html jquery asp.net-core


【解决方案1】:

ASP 为您在客户端的输入生成新的 ID,

所以你选择的 html 会是这样的

<select ID="City" class="form-control basic" asp-for="City" asp-items="@(new SelectList(ViewBag.Cities,"Id","ZoneName"))" readonly="@(Model.IsView ? true : false)">
     <option value="0" selected>Select</option>
</select>

为此生成的 id 是:City.ClientID, 所以为了访问这个选定的,你的 js 代码应该是这样的

...
success: function (data) {
                        
  alert(data.city);
  //debugger;
  $("#<%=City.ClientID%>").val(data.city);

},
...

注意 $("#&lt;%=City.ClientID%&gt;") --&gt; 是新生成的 id 将打印在选择器中

【讨论】:

  • jquery表单中如何获取这个clientid?
  • 已经在答案中发布了,试试我发布的内容! $("#&lt;%=City.ClientID%&gt;")
  • 它不工作
  • 您是否将选择更改为 mentiend 大写 ID,&lt;select ID="City"
【解决方案2】:

你可以试试这个

 $("#City option[value=data.city]").attr('selected', 'selected');

【讨论】:

    【解决方案3】:

    $('#City').val(data.city); 是为下拉列表设置选定值的正确方法。

    对于这个构造函数:new SelectList(ViewBag.Cities,"Id","ZoneName")),第一个参数是源,第二个参数是select中的每个选项value,第三个参数是每个选项显示的文本 在 html 中。

    也就是说Id代表选项值,ZoneName代表选项文本。

    当您为选择设置值时,您需要确保data.city 的值等于Id 的任何值。

    测试代码:

    型号:

    public class Test
    {
        public string City { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public string ZoneName { get; set; }
    }
    

    查看(索引.cshtml):

    @model Test
    <select id="CustomerName">
        <option>custom1</option>
        <option>custom2</option>
        <option>custom3</option>
    </select>
    <div class="form-group col-md-4">
        <label for="inputState">City</label>
        <select id="City" class="form-control basic" asp-for="City"
                asp-items="@(new SelectList(ViewBag.Cities,"Id","ZoneName"))">
            <option value="0" selected>Select</option>
        </select>
    </div>
    @section Scripts
    {
    <script>
        $("#CustomerName").change(function () {
            var CustomerName = $("#CustomerName").val();
    
            $.ajax({
                url: "/Home/FetchCustomerAddress",
                data: { userId: CustomerName  },
                type: "Get",
                success: function (data) {
                    alert(data.city);    
                    $('#City').val(data.city);
                },
                error: function (err) {
                    //console.error(err)
                    //alert("Internal server error.");
                }
            })
        });
    </script>
    }
    

    控制器:

    public IActionResult Index()
    {
        ViewBag.Cities = new List<City>()
        {
            new City(){Id=1,ZoneName="aa"},
            new City(){Id=2,ZoneName="bb"},
            new City(){Id=3,ZoneName="cc"}
        };
        return View();
    }
    
    public IActionResult FetchCustomerAddress(string userId)
    {
        //do your stuff...
        return Json(new Test() { City = "2" });
    }
    

    渲染视图:

    Ajax响应数据(在浏览器中按F12->点击Network面板->选择FetchCustomerAddress方法名->选择Response

    【讨论】:

    • 它的工作谢谢你
    • 嗨@Sharad Kulshrestha,如果我的回答可以帮助您解决您的问题,您能接受吗?参考:How to accept as answer。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    相关资源
    最近更新 更多