簡體   English   中英

AJAX Get呼叫發送空值到Controller

[英]AJAX Get call sending null to Controller

下面的代碼應該用於檢索任何特定價格日期/價格日期ID的記錄價格。 一切似乎都可以正常工作,但傳遞給Controller的值始終為null,“ undefined”,“”,否則以字符串形式傳遞時缺少值,並且沒有被傳遞/以as形式傳遞時在View中引發錯誤一個int。 我已經使用了可以解決此問題的模板,但看不到這里發生了什么。 不管最終計算可能會出現另一個問題,有人可以找出未傳遞ID值的原因嗎? 提前致謝!

HTML:

<div class="col-lg-8">
    @Html.LabelFor(m => m.PriceDate, "Pricing Date")
    @Html.DropDownListFor(m => m.PriceDate, Model.PricingDates, "--New Pricing--")
</div>

腳本:

$(function () {
    var $priceValue = $("#PriceDate").val(),
        $pID = { iD: $priceValue };
        $("#PriceDate").change(function () {
        if ($(this).val()) {
        //make AJAX call for historical Price data and populate table
            $.ajax({
                type: "GET",
                url: '@Url.Action("GetPrices", "Sales")',
                data: $pID,
                success: function (data) {
                //Fill data
                    $("#Prices").val(data);
                }
            });
        }
        else {
            //clear data
            $("#Prices").val('');
        }
        }).change();
});

控制器:

public ActionResult GetPrices(string iD)
{
    int priceID;
    Int32.TryParse(iD, out priceID);
    //priceID = iD;

    dbEntities db = new dbEntities();
    var selectedPrice = new List<PricesModel>();
    var accountPrices = db.uspGetPrices(priceID);

    //Do stuff

    return Json(selectedPrice, JsonRequestBehavior.AllowGet);
}

生成的HTML:

<div class="col-lg-8">
    <label for="PriceDate">Pricing Date</label>
    <select data-val="true" data-val-number="The field PriceDate must be a number." data-val-required="The PriceDate field is required." id="PriceDate" name="PriceDate"><option value="">--New Pricing--</option>
    <option value="2">1/4/2016 6:33 PM</option></select>
</div>

您甚至在更改事件之前( 特別是在DOM ready事件上 )正在讀取下拉菜單的所選選項的值。 因此,如果沒有將任何選項作為頁面加載的一部分而被pr選擇( 例如:create pag e),則將獲得undefined$priceValue變量的值。

您應該在change事件代碼中讀取下拉菜單的選定選項值。

$(function(){

    $("#PriceDate").change(function () {

       var $pID = { iD: $(this).val() };

       if ($(this).val()) {
          $.ajax({
            type: "GET",
            url: '@Url.Action("GetPrices", "Sales")',
            data: $pID,
            success: function (data) {
                alert(data);
                $("#Prices").val(data);
            }
         });
      }
      else {
         //clear data
          $("#Prices").val('');
      }
   }).change();

});

還要記住,您的當前代碼是在注冊了change事件代碼之后,在document ready下,在下拉列表中調用change()方法。 這意味着更改事件將始終在頁面DOM加載后觸發。 我不確定這是故意的!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM