我有一个DropDownListFor,当选择了不同的elementID / value时,应使用从GET ActionResult返回的Model数据填充相关元素,如果未选择任何值,则应清除相关TextBoxFor(s)中的条目。从DropDownListFor传递给ActionResult的字符串ID始终为null,从而生成错误。我已经尝试过使用变量进行AJAX数据调用,对数据进行字符串化以及读取许多StackOverflow问题,但是仍然会出现null异常。我是jQuery的新手,所以谁能看到为什么数据不包含值?

风景:

<div class="row">
    <div class="col-lg-4">
        @Html.LabelFor(m => m.AccountOwnerID, "Account Owner Name", new { @class = "req" })
        @Html.DropDownListFor(m => m.AccountOwnerID, Model.AccountOwners, "--New Owner--")
    </div>
    <div class="col-lg-4" id="AccountOwnerName">
        @Html.LabelFor(m => m.AccountOwner.AccountOwnerName, new { @class = "req"})
        @Html.TextBoxFor(m => m.AccountOwner.AccountOwnerName)
    </div>
</div>
<div class="row">
    <div class="col-lg-6" id="AccountOwnerPhoneNumber">
        @Html.LabelFor(m => m.AccountOwner.AccountOwnerPhoneNumber, "Owner Phone Number")
        @Html.TextBoxFor(m => m.AccountOwner.AccountOwnerPhoneNumber, new { @class = "form-control", data_parsley_required = "true" })
    </div>
    <div class="col-lg-6" id="AccountOwnerEmail">
        @Html.LabelFor(m => m.AccountOwner.AccountOwnerEmail, "Owner E-Mail Address")
        @Html.TextBoxFor(m => m.AccountOwner.AccountOwnerEmail, new { @class = "form-control", data_parsley_required = "true" })
    </div>
</div>

@section Scripts{

<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="/Scripts/jquery-ui-1.11.4.js"></script>

<script>
    $("#AccountOwnerID").change(function () {
        var $ownerName = $("#AccountOwner\\.AccountOwnerName"),
            $ownerEmail = $("#AccountOwner\\.AccountOwnerEmail"),
            $ownerPhone = $("#AccountOwner\\.AccountOwnerPhoneNumber"),
            $ownerValue = $("#AccountOwnerID").val(),
            $aOID = { ownerID : $ownerValue };
        if (this.value >= 1) {
            $.ajax({
                type: "GET",
                url: '/Sales/GetAccountOwnerInfo',
                data: JSON.stringify($aOID),
                success: function (data) {
                    //Fill data
                    $ownerName = data.AccountOwnerName;
                    $ownerEmail = data.AccountOwnerEmail;
                    $ownerPhone = data.AccountOwnerPhoneNumber;
                }
            });
        }
        else {
            //clear fields
            $ownerName.val('');
            $ownerEmail.val('');
            $ownerPhone.val('');
        }
    }).change();
</script>


控制器,返回一个模型,该模型具有AJAX成功分配给其的TextBoxFor(s)元素:

public ActionResult GetAccountOwnerInfo(string ownerID)
    {
        Int64 accountOwnerID = 0;
        Int64.TryParse(ownerID, out accountOwnerID);

        ProjectEntities projectDB = new ProjectEntities();
        var owner = projectDB.uspGetAccountOwnerInformation(accountOwnerID).FirstOrDefault();
        AccountOwnersModel accountOwner = new AccountOwnersModel()
        {
            AccountOwnerID = owner.AccountOwnerID,
            AccountOwnerName = owner.AccountOwnerName,
            AccountOwnerEmail = owner.AccountOwnerEmail,
            AccountOwnerPhoneNumber = owner.AccountOwnerPhone,
        };

        return Json(accountOwner, JsonRequestBehavior.AllowGet);
    }

最佳答案

首先,$ownerName = $("#AccountOwner\\.AccountOwnerName"),表示$ownerName是未定义的,因为您没有id="AccountOwner\\.AccountOwnerName"元素。 html helper方法通过使用id替换属性名称中的任何.(以及[]字符)来生成_属性,以避免出现jquery问题。它必须是$ownerName = $("#AccountOwner_AccountOwnerName")

其次,您不需要对数据进行字符串化(如果这样做,则需要指定contentType: 'json', ajax选项)。它应该是data: { ownerID: $(this.val() },。请注意,使用$(this)可以避免再次搜索DOM。

第三,$ownerName是一个jquery元素,因此要设置其值,它需要$ownerName.val(data.AccountOwnerName);

旁注:您对if (this.value >= 1)的用法表示有问题。您的助手正在使用<option value="">--New Owner--</option>生成其第一个选项,因此您应检查null

您的脚本应该是

// cache the elements since you repeatedly accessing them
var ownerName = $("#AccountOwner_AccountOwnerName"),
    ownerEmail = $("#AccountOwner_AccountOwnerEmail"),
    ownerPhone = $("#AccountOwner_AccountOwnerPhoneNumber");
$("#AccountOwnerID").change(function () {
  if ($(this).val()) {
    $.ajax({
      type: "GET",
      url: '@Url.Action("GetAccountOwnerInfo", "Sales")', // don't hard code your url's
      data: { ownerID: $(this).val() },
      success: function (data) {
        // Fill data
        ownerName.val(dataAccountOwnerName);
        ownerEmail.val(data.AccountOwnerEmail);
        ownerPhone.val(data.AccountOwnerPhoneNumber);
      }
    });
  } else {
    // clear fields
    ownerName.val('');
    ownerEmail.val('');
    ownerPhone.val('');
  }
})


旁注:由于您将int的值传递给方法,因此您的方法参数应为int ownerID。另外,您不需要响应中的AccountOwnerID值,因此您可以在控制器中创建一个匿名对象

public ActionResult GetAccountOwnerInfo(int ownerID)
{
  ProjectEntities projectDB = new ProjectEntities();
  var owner = projectDB.uspGetAccountOwnerInformation(ownerID).FirstOrDefault();
  var data = new
  {
    AccountOwnerName = owner.AccountOwnerName,
    AccountOwnerName = owner.AccountOwnerName,
    AccountOwnerPhoneNumber = owner.AccountOwnerPhone
  };
  return Json(data, JsonRequestBehavior.AllowGet);
}

10-06 12:22