【发布时间】:2022-01-19 05:06:24
【问题描述】:
我正在使用带有 vuejs 和 axios 的 asp.net 核心。我正在尝试使用我的 put API,但它没有通过对象模型。其余功能都可以正常工作,但只有 put 没有捕捉到对象。
请只关注函数更新事件
var app = new Vue({
el: '#app',
data: {
newStock: {
productId: 0,
description: "",
qty: 10,
},
selectedProduct: null,
loading: false,
editing: false,
products: [],
},
mounted: function () {
this.getStocks();
},
methods: {
clearValues: function () {
this.newStock = {
description: "",
qty: 10,
};
this.newStock.productId = this.selectedProduct.id ?? 0;
},
selectProduct: function (product) {
this.selectedProduct = product;
this.newStock.productId = product.id;
},
getStocks: function () {
this.loading = true;
axios.get('/Admin/stock')
.then(res => {
console.log(res);
this.products = res.data;
})
.catch(err => {
console.log(err);
})
.then(() => {
this.loading = false;
this.editing = false;
})
},
deleteStocks: function (id, index) {
this.loading = true;
axios.delete('/Admin/stock/' + id)
.then(res => {
console.log(res);
debugger;
this.selectedProduct.stocks.splice(index, 1);
})
.catch(err => {
console.log(err);
})
.then(() => {
this.loading = false;
this.editing = false;
})
},
updateStocks: function () {
this.loading = true;
var item = this.selectedProduct.stocks.map(e => {
return {
id: e.id,
description: e.description,
qty: e.qty,
productId: parseInt(this.selectedProduct.id)
};
});
axios.put('/Admin/stock', { obj: item })
.then(res => {
console.log(res);
//this.products = res.data;
})
.catch(err => {
console.log(err);
})
.then(() => {
this.loading = false;
this.editing = false;
})
},
addStock: function () {
this.loading = true;
axios.post('/Admin/stock', this.newStock)
.then(res => {
console.log(res);
debugger;
this.selectedProduct.stocks.push(res.data);
this.clearValues();
})
.catch(err => {
console.log(err);
})
.then(() => {
this.loading = false;
this.editing = false;
})
},
},
});
API 控制器 -
[HttpPut("stock")]
public async Task<IActionResult> EditStocks(Shop.Application.Stocks.UpdateStock.Request obj) => Ok(await new Application.Stocks.UpdateStock(ctx).Do(obj));
模型/逻辑 - 此处 Do 函数捕获空对象。
public class UpdateStock
{
private AppDbContext ctx;
public UpdateStock(AppDbContext context)
{
ctx = context;
}
public async Task<Response> Do(Request request)
{
var lstStocks = new List<Stock>();
foreach (var item in request.Stocks)
{
lstStocks.Add(new Stock
{
Id = item.Id,
Description = item.Description,
Qty = item.Qty,
ProductId = item.ProductId,
});
}
ctx.Stocks.UpdateRange(lstStocks);
await ctx.SaveChangesAsync();
return new Response
{
Stocks = request.Stocks
};
}
public class StockViewModel
{
public string Description { get; set; }
public int Qty { get; set; }
public int ProductId { get; set; }
public int Id { get; set; }
}
public class Request
{
public List<StockViewModel> Stocks { get; set; }
}
public class Response
{
public List<StockViewModel> Stocks { get; set; }
}
}
请指导我在这里做错了什么。
【问题讨论】:
-
如果您使用的是 asp.net core 是哪个版本?
-
我使用的是 .net core 6 版本
-
它会击中你的控制器吗?
-
是的……它击中了控制器
标签: c# vue.js asp.net-core .net-core axios