AJAX获取向ActionResult发送null变量

时间:2015-08-19 21:26:15

标签: javascript jquery ajax asp.net-mvc

我有一个DropDownListFor,当选择了不同的elementID /值时,应该使用从GET ActionResult返回的Model数据填充相关元素,或者如果没有选择值,则清除相关TextBoxFor中的条目。传递给ActionResult的DropDownListFor中的字符串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>

Controller,它返回一个模型,其中包含AJAX成功分配给TextBoxFor的元素:

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);
    }

1 个答案:

答案 0 :(得分:1)

首先$ownerName = $("#AccountOwner\\.AccountOwnerName"),意味着$ownerName未定义,因为您没有id="AccountOwner\\.AccountOwnerName"的任何元素。 html帮助器方法通过使用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);
}