AJAX 获取向控制器发送空值的调用
AJAX Get call sending null to Controller
下面的代码应该检索任何特定价格日期/价格日期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 后将始终触发更改事件。我不确定这是故意的!
相关文章:
- 如何将属性值调用到 javascript
- 映射数组ES6时考虑空值
- Model中的Typeahead返回空值以形成输入字段
- JavaScript-HTML表单到JSON(空值)和格式
- webkit输入类型=在错误日期发送空值的日期
- 为什么数据列表选项的id返回空值
- 如何使用敲除映射将空值映射到空的可观察数组
- 完整日历:在启动时传递空值
- 为什么此函数会过滤掉“空”值
- 通过 Yii2 表单插入数据时获取空值
- 从角度服务返回空值的变量
- Math.min.apply 返回 0 表示空值
- Angular材质md日期选择器中的空值
- 提示时检测空值
- 在循环中获取值,发送到另一个页面并使用该值调用catch数据
- Sails.js beforeValidate()清空值参数
- 从 Ajax 调用 4.5 ASP.net Post 方法中收到的空值
- AJAX 获取向控制器发送空值的调用
- Angular $resource在api初始化后被调用,导致返回空值
- 在node.js中调用递归函数时为空值