首页 > 解决方案 > 在剃刀页面中使用数据库中的数据选择(搜索)另一个字段时自动填充字段

问题描述

我有字段,例如公司、名字、姓氏,所以当我从数据库提供的列表中选择姓氏时,我想自动填充其他字段。我怎样才能做到这一点?

动作方法:


    public static IList<Adresse> GetAdresses(string lastname)
    {
        string sql = string.Format("SELECT * FROM Adresse WHERE 
        lastname like  '%{0}%'", lastname);
        SqlDataAdapter adapter = CreateDataAdapter(sql);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        IList<Adresse> list = new List<Adresse>();
        foreach (DataRow dr in dt.Rows)
        {
        Adresse item = new Adresse();
        foreach (DataColumn dc in dr.Table.Columns)
        {
        PropertyInfo p = item.GetType().GetProperty(dc.ColumnName);
        if (p != null && dr[dc] != DBNull.Value && p.CanWrite)
        {
        p.SetValue(item, dr[dc], null);
        }
        }
        list.Add(item);
        }
        return list;
    }

查看

<div class="table_row">
  <div class="table_cell" style="padding-bottom:5px;"> Firstname: </div>
  <div class="table_cell" style="padding-bottom:5px;"> @Html.EditorFor(m => m.head.FirstName) </div>
</div>
<div class="table_row">
  <div class="table_cell" style="padding-bottom:5px;"> LastName: </div>
  <div class="table_cell" style="padding-bottom:5px;"> 
@Html.DropDownListFor(m => m.head.LastName, selectList, new { @class = "form-control selectpicker", @Value = @Model.head.FirstName, //onchange = "this.form.submit();" }) 
    <script>
      $(document).ready(function() {
        $('.selectpicker').selectpicker({
          liveSearch: true,
          showSubtext: true
        });
      });
    </script>
  </div>
</div>

标签: asp.net-mvc

解决方案


由于您使用的是 jQuery,您可以向控制器中的操作发出 ajax 请求,该操作将返回地址信息。

$("#dropdownlist").change(function() {    
    $.ajax({
        type: 'POST',
        url: 'GetAddress',
        data: { lastname: $("#dropdownlistID").val() },
        success: function (data) {
            // fill address with data
        },
        error: function (ex) {
            console.log('Failed to retrieve data. Exception: ' + ex);
        }
    });
});

GetAddress()将您的方法的签名更改为:

public ActionResult GetAddress(string lastname)
{
    // your code to return address information
}

推荐阅读