【发布时间】:2021-04-16 03:12:23
【问题描述】:
这是我第一次在这里问。我只是想知道是否有办法将另一个模型中的模型数据从 ajax 发送到控制器。
这是我的模型:
public class mfItems
{
[Key]
[Display(Name = "Item ID")]
public string ItemID { get; set; }
[Required(ErrorMessage = "Required")]
[Display(Name = "Model Description")]
public string ItemModelDescription { get; set; }
[Display(Name = "Unit Price")]
[Required(ErrorMessage = "Required")]
public decimal ItemUnitPrice { get; set; }
}
还有我的另一个模特:
public class trnPurchaseOrderLists
{
public mfItems Items { get; set; }
public decimal Quantity { get; set; }
}
这是我的 ajax,在这个 ajax 中,我尝试记录 data.items.itemid,但这不是发送 id,而是当我删除 console.log(data.items.itemid) 和控制器 hey.Items.ItemID = id 时,另一个数量数据运行良好.
function change_quantity(id) {
var value = $('#' + id).val();
$.ajax({
type: "POST",
url: "@Url.Action("ChangeQuantity")",
data: { id: id, value: value },
dataType: "json",
success: function (data) {
console.log(data.items.itemid);
console.log(data.quantity);
}
});
}
最后是我的控制器
[HttpPost]
public trnPurchaseOrderLists ChangeQuantity(string id,decimal value)
{
trnPurchaseOrderLists hey = new trnPurchaseOrderLists();
hey.Items.ItemID = id;
hey.Quantity = value;
return hey;
}
我哪里错了?请帮忙谢谢。如果你发现我的英语很混乱,我很抱歉。我真的不擅长英语。非常感谢
【问题讨论】:
-
嗨 @JeffreyEstrera 欢迎来到 StackOverflow。
hey.Items是一个mfItems实例。要访问hey.Items.ItemID,您需要先在您的API 中实例化hey.Items。hey.Items = new mfItems();。那么你只能分配hey.Items.ItemID = id;。 -
您好,谢谢。实际上我没有使用 API。反正有没有不使用 API 来实现它?抱歉,我是 MVC Core 的新手
-
@JeffreyEstera,哎呀,声明
hey.Items = new mfItems();应该在你的控制器中用于这个ChangeQuantity方法,而不是 API。很抱歉提到的错误。 -
谢谢,我不再收到错误消息。然而还是有问题。这是我的 ID 未定义。但是通过查看我的输入 我认为这没有什么问题吗?正确的?因为我已经通过输入功能发送了 ID。这怎么还是未定义:?
-
嗨@Jeffrey,我认为您需要检查您的GET 方法(将数据绑定到视图),它是否已将
@item.Items.ItemID的值返回到您的视图中。接下来检查您的 HTML 输入元素id和change_quantity方法是否包含值。随意创建另一个帖子来提及您面临的问题,并Minimal Reproducible Example。谢谢。
标签: jquery ajax asp.net-core-mvc