У меня есть . NET Базовый веб-API с функциями crud
, когда я передаю объект типа (Product obj)
как json сериализации в действие, его значение приходит к действие хорошо , как вы можете видеть здесь ...
Но, когда я передаю такой параметр, как (int id)
как json сериализация, значение не поступает в действие как вы можете видеть здесь
, единственный способ - передать параметр как Строка запроса как ?id=5
, в этом случае значение поступает в действие , как вы можно посмотреть здесь
Теперь мне нужно передать параметр как json, так что ...
В чем разница между этими двумя случаями (json и строка запроса) ??
Как передать параметр как json, а не как строку запроса ??
это код контроллера
private readonly IProductRep rep;
public ProductController(IProductRep rep)
{
this.rep = rep;
}
[EnableCors("allow")]
[HttpPost]
public IActionResult GetAllProducts()
{
try
{
return Json(new { Result = "OK", Records = rep.GetAllProducts() });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
[EnableCors("allow")]
[HttpPost]
public JsonResult AddNewProduct(Product obj)
{
try
{
if (!ModelState.IsValid)
{
return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
}
Product product = rep.AddNewProduct(obj);
return Json(new { Result = "OK", Record = product });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
[EnableCors("allow")]
[HttpPost]
public JsonResult GetProductById(int id)
{
try
{
return Json( new { Result = "OK", Records = rep.GetProductById(id) });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
[EnableCors("allow")]
[HttpPost]
public IActionResult DeleteProduct(int id)
{
try
{
rep.DeleteProduct(id);
return Json( new { Result = "OK" });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
[EnableCors("allow")]
[HttpPost]
public JsonResult EditProduct(Product obj)
{
try
{
return Json( new { Result = "OK", Records = rep.EditProduct(obj) });
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
Это мой клиент код (я использую jtable)
$('#container').jtable({
title: 'Table of people',
actions: {
listAction:'http://localhost:62881/product/GetAllProducts',
createAction:'http://localhost:62881/product/AddNewProduct',
updateAction: 'http://localhost:62881/product/EditProduct',
deleteAction: 'http://localhost:62881/product/DeleteProduct'
},
fields: {
Id: {
key: true,
create:false,
edit:false,
list: true
},
ProductName: {
title: 'Name',
width: '40%'
},
Price: {
title: 'Price',
width: '20%'
},
ProductCode: {
title: 'Product Code',
width: '30%'
}
}
});
$('#container').jtable('load');
это то, что случилось с почтальоном при попытке отправить идентификатор как json
, но когда я добавляю id как Параметр в маршрутизации и отправить его в виде строки запроса, он работает , как вы можете увидеть здесь