[英]Passing JavaScript object to C#
我正在嘗試在Azure SQL數據庫中托管的表中創建新行。 我的前端是AngularJS,后端使用.NET中的C#。 這是我從前端傳遞對象的代碼:
var insertTicket = function (newTicket) {
return $http.post("http://localhost:50412/api/tickets", JSON.stringify(newTicket))
.then(function (response) {
console.log(response);
console.log("Insert Successful");
return;
});
這是我的后端代碼,用於接收數據並嘗試添加到數據庫中:
[Route("api/tickets")]
public HttpResponseMessage Post(Ticket t)
{
TicketsRepository.InsertTicket(t);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
在TicketRepisitory中:
public static void InsertTicket(Ticket tick)
{
var maxID = (from ticket in dataContext.Tickets
select ticket.id).Max();
var tick = new Ticket();
tick.id = maxID + 1;
dataContext.Tickets.Add(tick);
dataContext.SaveChanges();
}
這是我的票務類:
public partial class Ticket
{
//Properties
public int id { get; set; }
public string title { get; set; }
public string customer { get; set; }
public string barcode { get; set; }
public string assignedTo { get; set; }
public string category { get; set; }
public string importance { get; set; }
public Nullable<System.DateTime> openDate { get; set; }
public Nullable<System.DateTime> dueDate { get; set; }
public Nullable<System.DateTime> closedDate { get; set; }
public string comments { get; set; }
public string condition { get; set; }
public Nullable<int> workHours { get; set; }
//Relationships
public Employee Employee { get; set; }
public Employee Employee1 { get; set; }
public Equipment Equipment { get; set; }
}
我認為問題出在Post()希望有票證對象。 我嘗試搜索如何接收JSON數據並將其用於Ticket,但運氣不佳。
我的問題是我無法創建新行。 我的數據庫沒有任何變化。
在AngularJS中使用$http
數據時,您無需對對象進行JSON.stringify
,只需將對象本身作為第二個參數傳遞,如下所示:
var insertTicket = function (newTicket) {
return $http.post("http://localhost:50412/api/tickets", newTicket)
.then(function (response) {
console.log(response);
console.log("Insert Successful");
return;
});
首先,不需要為$ http.post()方法的第二個參數在newticket javascript對象上調用JSON.stringify()方法。
然后,在Web api方法中,使用名稱newTicket編寫類型為JObject的參數以接收發布的對象,並使用ToObject方法的通用版本將發布的數據轉換為所需的類型。 不要忘記為方法參數使用[FromBody]屬性。 webapi的代碼如下所示:
[Route("api/tickets")]
public HttpResponseMessage Post([FromBody]JObject newTicket)
{
var t = newTicket.ToObject<Ticket>();
TicketsRepository.InsertTicket(t);
HttpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.