AJAX获取发送空变量的ActionResult [英] AJAX Get sending null variable to ActionResult

查看:113
本文介绍了AJAX获取发送空变量的ActionResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DropDownListFor即,当选择了不同的elementID /值,应填充相关元素与模型数据从一个GET的ActionResult退回,或清除从该相关TextBoxFor(多个)中的条目,如果没有选择的值。从传递到的ActionResult的DropDownListFor的字符串ID总是空,产生错误。我已经用变量的AJAX数据呼叫,字符串化 - 荷兰国际集团的数据,读很多的StackOverflow问题试过了,但空异常仍会发生。我是新来的jQuery,所以任何人都可以看到为什么数据不包含价值呢?

视图:

 < D​​IV CLASS =行>
    < D​​IV CLASS =COL-LG-4>
        @ Html.LabelFor(M => m.AccountOwnerID,帐户所有者姓名,新{@class =REQ})
        @ Html.DropDownListFor(M => m.AccountOwnerID,Model.AccountOwners - 新Owner--)
    < / DIV>
    < D​​IV CLASS =COL-LG-4ID =AccountOwnerName>
        @ Html.LabelFor(M => m.AccountOwner.AccountOwnerName,新{@class =REQ})
        @ Html.TextBoxFor(M => m.AccountOwner.AccountOwnerName)
    < / DIV>
< / DIV>
< D​​IV CLASS =行>
    < D​​IV CLASS =COL-LG-6ID =AccountOwnerPhoneNumber>
        @ Html.LabelFor(M => m.AccountOwner.AccountOwnerPhoneNumber,所有者电话号码)
        @ Html.TextBoxFor(M => m.AccountOwner.AccountOwnerPhoneNumber,新{@class =表单控制,data_parsley_required =真正的})
    < / DIV>
    < D​​IV CLASS =COL-LG-6ID =AccountOwnerEmail>
        @ Html.LabelFor(M => m.AccountOwner.AccountOwnerEmail,所有者电子邮件地址)
        @ Html.TextBoxFor(M => m.AccountOwner.AccountOwnerEmail,新{@class =表单控制,data_parsley_required =真正的})
    < / DIV>
< / DIV>

@section脚本{

<脚本的src =〜/脚本/ jQuery的-2.1.3.js>< / SCRIPT>
<脚本的src =/脚本/ jQuery的-UI-1.11.4.js>< / SCRIPT>

<脚本>
    $(#AccountOwnerID)。改变(函数(){
        变量$ OWNERNAME = $(#AccountOwner \\。AccountOwnerName),
            $ ownerEmail = $(#AccountOwner \\。AccountOwnerEmail),
            $ ownerPhone = $(#AccountOwner \\。AccountOwnerPhoneNumber),
            $ ownerValue = $(#AccountOwnerID)。VAL()
            $ aOID = {OWNERID:$ ownerValue};
        如果(THIS.VALUE> = 1){
            $阿贾克斯({
                键入:GET,
                网址:'/销售/ GetAccountOwnerInfo',
                数据:JSON.stringify($ aOID)
                成功:功能(数据){
                    //填充数据
                    $ OWNERNAME = data.AccountOwnerName;
                    $ ownerEmail = data.AccountOwnerEmail;
                    $ ownerPhone = data.AccountOwnerPhoneNumber;
                }
            });
        }
        其他 {
            //明确的领域
            $ ownerName.val('');
            $ ownerEmail.val('');
            $ ownerPhone.val('');
        }
    })。更改();
< / SCRIPT>
 

控制器,它返回一个模型元素到了AJAX成功分配给TextBoxFor(S):

 公众的ActionResult GetAccountOwnerInfo(字符串OWNERID)
    {
        Int64的accountOwnerID = 0;
        Int64.TryParse(OWNERID,出accountOwnerID);

        ProjectEntities projectDB =新ProjectEntities();
        VAR所有者= projectDB.uspGetAccountOwnerInformation(accountOwnerID).FirstOrDefault();
        AccountOwnersModel accountOwner =新AccountOwnersModel()
        {
            AccountOwnerID = owner.AccountOwnerID,
            AccountOwnerName = owner.AccountOwnerName,
            AccountOwnerEmail = owner.AccountOwnerEmail,
            AccountOwnerPhoneNumber = owner.AccountOwnerPhone,
        };

        返回JSON(accountOwner,JsonRequestBehavior.AllowGet);
    }
 

解决方案

首先 $ OWNERNAME = $(#AccountOwner \\。AccountOwnerName),将意味着 $ OWNERNAME 是不确定的,因为你没有用 ID =AccountOwner \\。AccountOwnerName的任何元素。在HTML辅助方法生成 ID 通过使用属性替换任何(和 [] 字符)的属性名称与 _ 来避免与jQuery的问题。这将需要 $ OWNERNAME = $(#AccountOwner_AccountOwnerName)

其次,你并不需要字符串化数据(如果你这样做,那么你需要指定的contentType:JSON, AJAX选项)。它应该是数据:{OWNERID:$(this.val()} 注意使用 $(这)来避免不得不再次搜索的DOM

第三, $ OWNERNAME 是一个jQuery元素,以便将其值设置,它需要 $ ownerName.val(data.AccountOwnerName);

旁注:你的的使用,如果(THIS.VALUE> = 1)暗示了什么。您的帮助是产生了第一个选项与<期权价值=> - 新业主 - < /选项> ,所以你应该检查

您的脚本应该是

  //缓存的元素,因为你重复访问它们
VAR OWNERNAME = $(#AccountOwner_AccountOwnerName),
    ownerEmail = $(#AccountOwner_AccountOwnerEmail),
    ownerPhone = $(#AccountOwner_AccountOwnerPhoneNumber);
$(#AccountOwnerID)。改变(函数(){
  如果($(本).VAL()){
    $阿贾克斯({
      键入:GET,
      网址:@ Url.Action(GetAccountOwnerInfo,销售)',//做C本网址不难$ C $
      数据:{OWNERID:$(本).VAL()},
      成功:功能(数据){
        //填充数据
        ownerName.val(dataAccountOwnerName);
        ownerEmail.val(data.AccountOwnerEmail);
        ownerPhone.val(data.AccountOwnerPhoneNumber);
      }
    });
  } 其他 {
    //明确的领域
    ownerName.val('');
    ownerEmail.val('');
    ownerPhone.val('');
  }
})
 

边注:由于您传递一个值,该值 INT 的方法,你的方法参数应该是 INT OWNERID 。你也不用在响应 AccountOwnerID 的值,这样你可以只在控制器上创建一个匿名对象

 公众的ActionResult GetAccountOwnerInfo(INT OWNERID)
{
  ProjectEntities projectDB =新ProjectEntities();
  VAR所有者= projectDB.uspGetAccountOwnerInformation(OWNERID).FirstOrDefault();
  VAR数据=新
  {
    AccountOwnerName = owner.AccountOwnerName,
    AccountOwnerName = owner.AccountOwnerName,
    AccountOwnerPhoneNumber = owner.AccountOwnerPhone
  };
  返回JSON(数据,JsonRequestBehavior.AllowGet);
}
 

I have a DropDownListFor that, when a different elementID/value is selected, should populate related elements with Model data returned from a GET ActionResult, or clear the entries from the related TextBoxFor(s) if no value is selected. The string ID from the DropDownListFor passed to the ActionResult is always null, generating an error. I've tried using variables for the AJAX data call, stringify-ing the data, and reading many StackOverflow questions, but the null exception still occurs. I'm new to jQuery, so can anyone see why the data doesn't contain a value?

The View:

<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>

The Controller, which returns a model with elements to which the AJAX success assigns to the 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);
    }

解决方案

Firstly $ownerName = $("#AccountOwner\\.AccountOwnerName"), will mean $ownerName is undefined since you don't have any elements with id="AccountOwner\\.AccountOwnerName". The html helper methods generate id attributes by using the replacing any . (and [ and ] characters) in the property name with _ to avoid issues with jquery. It would need to be $ownerName = $("#AccountOwner_AccountOwnerName")

Secondly, you do not need to stringify the data (and if you do, then you need to specify the contentType: 'json', ajax option). It should be data: { ownerID: $(this.val() },. Note the use of $(this) to avoid having to search the DOM again.

Thirdly, $ownerName is a jquery element so to set its value, it needs to $ownerName.val(data.AccountOwnerName);

Side note: your usage of if (this.value >= 1) suggests something wrong. Your helper is generating its first option with <option value="">--New Owner--</option> so you should be checking for null.

Your script should be

// 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('');
  }
})

Side note: Since your passing a value which is int to the method, your method parameter should be int ownerID. Also you don't need the value of AccountOwnerID in the response so you could just create an anonymous object in the controller

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

这篇关于AJAX获取发送空变量的ActionResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆