我会尝试得到这样的结果:
function GetPrice() {
var url = '@Url.Action("GetAdditionalPrice")';
$.post(url, { additionalsId: $("input[name=selectedAdditionals]").val }),
function(data) {
$("#TotalAmount").val(data);
}; //View
}
public ActionResult GetAdditionalPrice(string[] additionalsId)
{
decimal price = 0;
foreach (var id in additionalsId)
{
var aid = int.Parse(id);
price += db.ContractAdditionals.Where(ca => ca.ContractAdditionalID == aid).Select(ca => ca.Price).Single();
}
return Json(price, JsonRequestBehavior.AllowGet);
}//Controller
为什么string[] additionalsId
参数始终未定义?如何将参数发布到控制器并将结果设置为#TotalAmount
?
答案 0 :(得分:0)
您错过了()
声明.val
。这应该是在控制台中抛出JS错误。
要传回一个数组,您还需要使用所选值
构建一个数组试试这个:
function GetPrice() {
var url = '@Url.Action("GetAdditionalPrice")';
var items = new Array();
$.each($("input[name=selectedAdditionals]:checked"), function () {
items.push($(this).val());
});
$.post(url, { additionalsId: items }),
function(data) {
$("#TotalAmount").val(data);
}; //View
}
答案 1 :(得分:0)
试试这个
function GetPrice() {
var url = '@Url.Action("GetAdditionalPrice")';
$.post(url, { additionalsId: $("input[name=selectedAdditionals]").val() }),
function(data) {
$("#TotalAmount").val(data.result);
}; //View
}
public ActionResult GetAdditionalPrice(string[] additionalsId)
{
decimal price = 0;
foreach (var id in additionalsId)
{
var aid = int.Parse(id);
price += db.ContractAdditionals.Where(ca => ca.ContractAdditionalID == aid).Select(ca => ca.Price).Single();
}
return Json(new {result=price}, JsonRequestBehavior.AllowGet);
}//Controller
答案 2 :(得分:0)
解决了
function GetPrice() {
var url = '@Url.Action("GetAdditionalPrice")';
var items = new Array();
$("input[name=selectedAdditionals]:checked").each(function () {
items.push($(this).val());
});
var postData = { additionalsId: items };
$.ajax({
type: "POST",
url: url,
data: postData,
success: function (data) {
$("#TotalAmount").val(data.result);
},
dataType: "json",
traditional: true
});
}
感谢您的帮助:)