我嘗試使用“資料:”以多種方式使用 ajax 傳遞多個引數,但并非所有引數都被傳遞。
這是 OnPost PageModel 方法:
public JsonResult OnPostCreate(Product product, int id, string name)
{
return new JsonResult(new { success = true });
}
阿賈克斯:
function SaveMe() {
var product = {
ProductId: 1,
ProductName: 'Any',
UnitsInStock: 2,
Discontinued: true,
};
var id = 1;
var name = 'Product1';
var data = {};
data.product = product;
data.id = id;
data.name = name;
$.ajax({
url: `?handler=Create`,
method: "post",
contentType: "application/json",
headers: {
"XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(data)
})
.done(function (response) {
alert(response.success);
});
};
而且我不想使用“url:”ajax中的引數,例如:
url: `?handler=Create&id=2&name=Product1`
誰能幫忙?謝謝大家。
uj5u.com熱心網友回復:
可能這可以幫助你;
function SaveMe() {
var product = {
ProductId: 1,
ProductName: 'Any',
UnitsInStock: 2,
Discontinued: true,
};
var id = 1;
var name = 'Product1';
product.id = id; // ----------------------- (*1)
product.name = name; // ------------------- (*2)
$.ajax({
url: `?handler=Create`,
method: "post",
contentType: "application/json",
headers: {
"XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val()
},
data: product // ----------------------- (*3)
})
.done(function (response) {
alert(response.success);
});
};
*1:在服務器端,您的產品模型沒有“id”和“name”屬性,但是當您想一起使用它們時,您需要一起準備客戶端模型。
*2:也是另一種選擇;使用 [NotMapped] 屬性向 Product 模型添加“id”和“name”屬性。未映射屬性可以幫助您將額外的屬性添加到模型中,這些屬性未在資料庫表中顯示。
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public int UnitsInStock { get; set; }
public bool Discontinued { get; set; }
[NotMapped]
public int id { get; set; }
[NotMapped]
public string name { get; set; }
{
*3 : 不需要使用 JSON.stringify。將資料作為 json 發布。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/483387.html
