2015-12-04 4 views
12

角度付きフォームのJSONデータをASP.NET5 MVC6コントローラアクションに投稿しようとしています。モデルのバインダーは動作していないようです。私がここで何が欠けているか分からない。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. 
      }); 
     } 
    }; 
}]) 

マイビューモデル:私は要求を行うと、HTTPヘッダーがある

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; } 
} 

..

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データがモデルにバインドされないのはなぜですか?確かに私は単純な何かのためのカスタムモデルのバインダーが必要ないのですか?

+0

を作業得るためにの公開IActionResult SubmitTest(ストリングモデル 'に' 'パブリックIActionResult SubmitTest(QTestViewModelモデル)を変更してみてください を使用していた を動作しませんでした) 'をクイックテストとして返し、それが戻ってくるものを確認してください –

+1

また、' public IActionResult SubmitTest([FromBody] QTestViewModel model) ' –

+0

' JsonRequestBehavior.AllowGet'がありません。 'return Json(" true "、JsonRequestBehavior.AllowGet);' –

答えて

12

MVC 5以前のバージョンでは、コントローラでモデルを受信するのにコードで十分でした。 しかしMVC 6にまた、あなたのコントローラのアクションに[FromBody]パラメータを設定する必要があります。

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

わからない、なぜこれがMVC 6で要件ですが、あなたはFromBodyを追加いけない場合、あなたのモデルは、そのデフォルト値を保持します属性。

  • たとえば、Web API tutorialを公式ドキュメントにチェックしてください。ソースに掘りいくつかの後

  • は、BodyModelBinderだけで、具体的[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も呼び出す必要があります。いつか

var jsonResult=json("true"); 
jsonResult.maxJsonLength=int32.maxValue 
return jsonresult; 

それを使用するために、より良いJSONで起こった

+0

に変更してください。これは動作しません。 viewmodel内のすべての値は、コントローラに到達するとnullになります。 –

1

は、それはあなたのために役立つことを願っています。

1

[編集]この回答は間違っています。私の問題は、オブジェクトのプロパティの1つと同じ名前のActionパラメータが原因です。これにより、あいまいさを防ぐためにプレフィックスを使用するMVCが発生しました。私はそれがあいまいであることに同意せず、Githubでこれについて議論しています。


これについてGithubにエラーが記録されました。あなたのパラメータがパラメータのタイプのCamelCaseとして名前が付けられていない場合、ペイロードのフィールドの前にパラメータ名が付くと予想されます。

[Bind(Prefix = "")]をアクションのパラメータの前に追加することでこれを修正できます。 public IActionResult SubmitTest([Bind(Prefix="")]QTestViewModel model)

0

Ok @ダニエルJ.G. answereは私のために、私は[FromForm]ではなく[FromBody] bingingが

[HttpPost] 
public IActionResult SubmitTest([FromForm]QTestViewModel model) 
{ 
    return Json("true"); 
} 
関連する問題