AJAX 获取向控制器发送空值的调用

AJAX Get call sending null to Controller

本文关键字:空值 调用 获取 控制器 AJAX      更新时间:2023-09-26

下面的代码应该检索任何特定价格日期/价格日期ID的记录价格。 一切似乎都正常,除了传递给控制器的值在作为字符串传递时始终为 null、"undefined"、" 或以其他方式缺少值,并且在作为 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 就绪事件上)就正在读取下拉列表的选定选项的值。因此,如果没有一个选项被 pr 选择作为页面加载的一部分(例如:创建页面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 . 这意味着在加载页面 DOM 后将始终触发更改事件。我不确定这是故意的!