【问题标题】:MVC Core Action not binding from angularjs POSTMVC 核心操作未从 angularjs POST 绑定
【发布时间】:2017-04-04 14:22:25
【问题描述】:

我在从简单的 angularjs 页面将对象发布到 MVC Core 控制器的位置时遇到问题。

我的 MVC 操作中的对象没有绑定,尽管对象本身不为 null,这是常见的问题。

谁能看出我做错了什么?

这是我的角度服务代码:

this.getQuote = function (priceRequest) {
    return $http.post('/quote/getcost', { priceRequest });
};

调用者:

quoteService.getQuote(this.quoteData).then(function (cost) {
    $scope.quoteData.quoteCost = cost.data;
});

this.quoteData 在哪里:

$scope.quoteData = {
                detailLevel: '0',
                fileLengthHours: 0,
                fileLengthMinutes: 1,
                excessiveSpeakersCount: 1,
                industry: null,
                deliveryTime: '1',
                additionalInformation: '',
                quoteCost: null
            };

这是有效载荷

这是 POST:

最后是我的 C# MVC Core 操作:

[HttpPost]
public JsonResult GetCost([FromBody]PriceRequest priceRequest)
{
    var price = _priceCalculator.GetPrice(priceRequest);

    return new JsonResult(price);
} 

虽然发布的对象不为空,但没有任何值被绑定:

这是 PriceRequest 对象:

public class PriceRequest
{
    public JobDetailLevel DetailLevel { get; set; }

    public int FileLengthHours { get; set; }

    public int FileLengthMinutes { get; set; }

    public int? ExcessiveSpeakersCount { get; set; }

    public JobIndustry Industry { get; set; }

    public JobDeliveryTime DeliveryTime { get; set; }

    public string AdditionalInformation { get; set; }        
}

谁能看出我做错了什么?

【问题讨论】:

  • 您的 .Net PriceRequest 对象是如何定义的?
  • 刚刚添加到问题布拉德。任何不是字符串或 int 的都是枚举
  • 您的“POST”屏幕截图缺少正文。身体是什么样子的?
  • 上面的payload截图有吗?
  • priceRequest{DetailLevel: "0"... 看起来不对,我希望更像priceRequest{DetailLevel:{...etc}} 基本上你的 json 看起来不正确

标签: angularjs asp.net-core-mvc


【解决方案1】:

好的,感谢这篇文章: Asp.net core MVC post parameter always null

我需要将此添加到我的 startup.cs:

.AddJsonOptions(jsonOptions =>
{
  jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
});

感谢那些试图提供帮助的人。

【讨论】:

    【解决方案2】:

    尝试从角度侧的 priceRequest 变量周围删除 { }

    喜欢:

    return $http.post('/quote/getcost', priceRequest);
    

    【讨论】:

    • 我在服务器端的对象变成了 null 这样做
    • 它不能“变为空”。您将 json 对象作为参数传递给此函数: this.getQuote = function (priceRequest) { } 通过将 priceRequest 与 { } 包装在一起,您将 json 对象包装在另一个对象中,因此它不会绑定主体服务器端
    猜你喜欢
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 2018-07-28
    • 1970-01-01
    • 2018-11-11
    • 2021-11-18
    • 1970-01-01
    相关资源
    最近更新 更多