MVC ajax POST 关于 ApplicationUser 的信息

MVC ajax POST info about ApplicationUser

我有一个包含 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; }
}

然后我尝试 post 使用 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,因为它是 posted 一个字符串。我做错了什么?提前感谢您的帮助。

如果我们有一个 class "A" 包含对 "B" 的引用并且这个 "B" 也有对 "A" 的引用(即使不是直接),序列化过程不起作用。就像 "infinite loop"。 我建议您将 ApplicationUserUser 的类型)更改为 string 并在需要时使用它来获取模型(在代码隐藏中)。

如果您需要从控制器内部获取用户,请使用 ControllerUser 属性。 如果您从视图中需要它,将在 ViewData 中填充您特别需要的内容,或者您​​可以调用 User.

例如。 @User.Identity.Name

谢谢 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();
   }   

我得到了我想要的:)