我有一个由ApllicationUser组成的实体作为外键:
public class Trades
{
public int ID { get; set; }
public double Price { get; set; }
public double Volume { get; set; }
public string InstrumentName { get; set; }
public ApplicationUser User { get; set; }
}
然后我尝试使用AJAX发布交易。
var tradeData = {
"Price": 1,
"Volume": 1,
"InstrumentName": "instrumentName",
"User": "@User.Identity.Name"
};
$.ajax({
url: "/api/TradesAPI/",
method: "POST",
data: JSON.stringify(tradeData),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function () {
alert('executed!');
},
error: function (error) {
alert("Transacion has not been executed");
}
});
不幸的是,ApplicationUser没有被序列化为ApplicationUSer,因为它发布了一个字符串。我做错了什么?感谢您提前提供任何帮助。
答案 0 :(得分:2)
如果我们有一个包含对“B”的引用的类“A”,并且这个“B”也引用了“A”(即使不是直接的),序列化的过程也不起作用。这就像一个“无限循环”。
如果您需要,我建议您将ApplicationUser
(User
的类型)更改为string
并使用它来获取模型(代码隐藏)。
如果您需要从控制器中获取用户,请使用User
的{{1}}属性。
如果您在视图中需要它,则会在Controller
中填充您特别需要的内容,或者只需拨打ViewData
。
实施例。 User
答案 1 :(得分:1)
谢谢Indrit Kello。我改变了我的模型,所以我有
public class Trades
{
public int ID { get; set; }
public double Price { get; set; }
public double Volume { get; set; }
public string InstrumentName { get; set; }
public string UserId { get; set; }
}
我决定在API控制器中获取有关用户的信息,该控制器在视图中获取有关用户的数据。
public void CreateTradeAPI(Trades trade)
{
trade.UserID =User.Identity.Name;
_context.UsersTrades.Add(trade);
_context.SaveChanges();
}
我有我想要的东西:)