2015-12-04 82 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. 
      }); 
     } 
    }; 
}]) 

我的視圖模型:

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數據不能綁定到我的模型?當然,我不需要一個如此簡單的自定義模型綁定器?

+0

嘗試改變'公共IActionResult SubmitTest(QTestViewModel模型)'來'公共IActionResult SubmitTest(弦模型)'作爲一個快速測試,看看它回來什麼 –

+1

也嘗試'公共IActionResult SubmitTest([FromBody] QTestViewModel模型)' –

+0

你缺少'JsonRequestBehavior.AllowGet'。更改爲'返回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

+0

這不起作用。視圖模型內部的所有值在到達控制器時均爲空。 –

1

有時它與JSON發生更好地使用它

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

希望這將幫助你。

1

看來這個答案不正確。我的問題是由Action參數被命名爲與該對象的屬性之一相同。這導致MVC使用前綴來防止歧義。我不同意這是模棱兩可的,我正在討論Github


我剛剛在Github上記錄這個錯誤。看起來,如果你的參數沒有被命名爲參數類型的CamelCase,那麼它希望有效載荷中的字段以參數名稱作爲前綴。

您可以通過在Action的參數前面添加[Bind(Prefix =「」)]來解決此問題。 public IActionResult SubmitTest([Bind(Prefix="")]QTestViewModel model)

0

Ok @Daniel J.G.的answere沒有爲我 工作,我不得不使用 [FromForm]而不是[FromBody]要暴食工作

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