当前位置:  开发笔记 > 编程语言 > 正文

ASP.NET5 MVC6的模型绑定问题

如何解决《ASP.NET5MVC6的模型绑定问题》经验,为你挑选了1个好方法。

我试图在角色表单上发布一些JSON数据到我的ASP.NET5 MVC6控制器动作.模型绑定器似乎不起作用.不知道我在这里缺少什么.

我的ASP控制器:

public class DefaultController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult SubmitTest(QTestViewModel model)
    {
        return Json("true");
    }
}

我的角度控制器:

angular.module("testActiveMq", [])
.controller("MqTestController", ["$scope", "$http", function ($scope, $http) {
    // Submit Form
    $scope.submitForm = function () {
        debugger;
        var formData = (this.data) ? angular.toJson(this.data) : null;
        if (formData && this.qForm && this.qForm.$valid) {
            $http({
                url: "/Default/SubmitTest",
                data: formData,
                method: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8"
            })
            .then(function successCallback(response) {
                debugger;
                // this callback will be called asynchronously
                // when the response is available
            }, function errorCallback(response) {
                debugger;
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
        }
    };
}])

我的视图模型:

public class QTestViewModel
{
    public string MqBrokerUri { get; set; }

    public string ClientId { get; set; }

    public string UserName { get; set; }

    public string Password { get; set; }

    public int TotalRequests { get; set; }

    public int MaxConcurrentRequests { get; set; }

    public int DelayBetweenThreads { get; set; }
}

当我发出请求时,HTTP标头是......

POST /Default/SubmitTest HTTP/1.1
Host: localhost:50877
Connection: keep-alive
Content-Length: 225
Accept: application/json, text/plain, */*
Origin: http://localhost:50877
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:50877/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

我的表单数据看起来像..

{"MqBrokerUri":"ssl://broker-uri:1616?transport.acceptInvalidBrokerCert=true","ClientId":"MqLoadTest","UserName":"myunm","Password":"mypwd","TotalRequests":100,"MaxConcurrentRequests":10,"DelayBetweenThreads":1}

我觉得我错过了一些非常明显的东西.为什么我的JSON数据不能绑定到我的模型?当然,我不需要定制模型粘合剂来实现这么简单的事情吗?



1> Daniel J.G...:

您的代码足以在MVC 5及更早版本中接收控制器中的模型.但是在MVC 6中,您还需要[FromBody]在控制器操作中设置参数:

[HttpPost]
public IActionResult SubmitTest([FromBody]QTestViewModel model)
{
    return Json("true");
}

不确定为什么这是MVC 6中的要求,但是如果你不添加FromBody属性,你的模型将保持其默认值.

检查官方文档中的Web API教程.

在深入挖掘源代码之后,似乎BodyModelBinder只会接受专门启用了body绑定源的模型,这样就完成了添加[FromBody]属性.

var allowedBindingSource = bindingContext.BindingSource;
if (allowedBindingSource == null ||
    !allowedBindingSource.CanAcceptDataFrom(BindingSource.Body))
{
    // Formatters are opt-in. This model either didn't specify [FromBody] or specified something
    // incompatible so let other binders run.
    return ModelBindingResult.NoResultAsync;
}

PS.Angular默认是字符串化json对象,但如果你使用类似jQuery的东西,你还需要手动调用JSON.stringify.

推荐阅读
刘美娥94662
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有