【问题标题】:Dynamically populate model fields in a view on dropdownlist selection in asp.net mvc在 asp.net mvc 中的下拉列表选择视图中动态填充模型字段
【发布时间】:2019-09-03 04:19:05
【问题描述】:

我在 ASP.NET MVC 应用程序中有一个视图,其中包含一个下拉列表和其他文本字段。下拉列表中填充了来自特定目录的文件名。因此,在从下拉列表中选择特定文件名时,我想用所选文件上的内容填充其他文本字段。文件的读取已经处理完毕。

从下拉列表中选择文件名后,我正在努力填写文本字段。

我该怎么做?

<div class="col-lg-4">
    @Html.DropDownList("cardProgram", null, "--Select--", new { @class = "form-control input-group-lg" })
</div>

【问题讨论】:

  • 使用 ajax 来执行控制器操作,该操作将查找字段所需的数据,将它们放入模型中并将该模型作为 json 返回。 ajax 调用的成功函数将查看来自服务器的响应并将值分配给 html 输入
  • @SINETHEMBA PAULA 将您的其他文本字段添加到问题中,然后在选择下拉列表时说出您希望绑定到该输入字段的值。

标签: asp.net-mvc model-view-controller controller dropdownlistfor


【解决方案1】:

我终于让它工作了。见下文 : html代码:

@Html.LabelFor(m => m.cardProgram, new { @class = "col-lg-2" })
<div class="col-lg-4">
     @Html.DropDownListFor(m => m.cardProgram, null, "--Select Card Profile--", new
                           {
                               @class = "col-lg-4 form-control input-group-lg",
                               @onchange = "BindProfile()"

                           })
</div>

ajax 代码:

    <script>
        function BindProfile() {
            var selectedProfile = $('#cardProgram').val();
            $.ajax({
                url: '/CardCreation/BindProfile',
                type: "GET",
                dataType: "JSON",
                data: { cardProgram: selectedProfile },
                success: function (profile) {
                    $("#sBin").val(profile.card.bin)
                    $("#IsChip").val(profile.card.chip)

                    $("#IsBatches").val(profile.output.splitBatches)
                    $("#BatchSize").val(profile.output.batchSize)
                    $("#SplitPostcard").val(profile.output.splitPostcardFile)

                    $("#SubCat").val(profile.batchDetails.subcategory)
                    $("#UserCodeIncrement").val(profile.batchDetails.usercodeIncrement)
                    $("#ExpiryDate").val(profile.batchDetails.expiryWindowMM)

                    $("#Bureau").val(profile.chipDetails.bureau)
                    $("#BatchType").val(profile.chipDetails.batchType)
                    $("#EffectiveDate").val(profile.chipDetails.effectiveDateOffsetMM)

                    $("#ServiceCode").val(profile.emvApplications[0].serviceRestrictionCode)



                }
            });
        }
    </script>

控制器代码:


public async Task<ActionResult> BindProfile(string cardProgram)
        {
            var profile = new Profile();
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:59066/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                ViewBag.country = "";
                HttpResponseMessage response = await client.GetAsync(client.BaseAddress + "api/CardCreation/GetSelectedCardProfile?selectedProfile=" + cardProgram);
                if (response.IsSuccessStatusCode)
                {
                    //profile = response.Content.ReadAsAsync<Profile>().Result;
                    profile = JsonConvert.DeserializeObject<Profile>(response.Content.ReadAsStringAsync().Result);
                    return Json(profile, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(profile, JsonRequestBehavior.AllowGet); ;
                }
            }
        }

【讨论】:

    【解决方案2】:

    Ajax 代码:

    $(document).ready(function () {
            $("#FileDDL_ID").change(function () {
                var file = $('#FileDDL_ID option:selected').text();
    
                $.ajax({
                    url: "@Url.Action("YourAction", "Controller")",
                    type: "POST",
                    dataType: "json",
                    data: { filename: file }, //pass file as parameter to controller
                    async: false,
    
                    error: function () {
                    },
    
                    //assuming your data property is called fileDetail1
                    success: function (data) {
                        if (Object.keys(data).length > 0) {
                            $('#fileDetailtxtBox1').val(data[0].fileDetail1);                          
                            $('#fileDetailtxtBox2').val(data[0].fileDetail2);
                        }
                    }
                });
            });
        });
    

    控制器代码:

    [HttpPost]
    public JsonResult YourAction(string filename)
    {
       using (var db = new DataContext())
       {
          //use filename as condition
          var details = db.YourDbset.Condition.ToList();
          return Json(details, JsonRequestBehavior.AllowGet);
       }
    }
    

    希望这很清楚,我已尝试根据您的问题命名变量。因此,基本上,您将下拉列表中的选定值传递给 Controller 操作,并获取相关数据并使用 jQuery Ajax 填充字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-16
      • 2012-04-10
      • 1970-01-01
      • 2013-07-03
      • 2015-01-02
      相关资源
      最近更新 更多