2015-06-21 57 views
2

我目前在网站上的工作只是为了好玩利用AngularJS和ASP.net到ASP.NET,这个职位是一个更广义的问题,因为我不知道究竟是如何做到这一点,我或多或少地想知道最佳实践是什么。目前,我有这样邮政JSON通过AngularJS

$scope.submit = function() { 
    console.log(JSON.stringify($scope.form)); 
    $http.post("/post/new", "'" + JSON.stringify($scope.form) + "'"). 
     success(function (data, status, headers, config) { 
      console.log("Success") 
      $location.path("/news"); 
     }).error(function (data, status, headers, config) { 
      console.log("Error"); 
     }); 
}; 

然后我相应的Asp.net代码角的方法:

[HttpPost][Route("New")] 
    public IHttpActionResult New([FromBody] string input) 
    { 
     JObject json = JObject.Parse(input); 
     Post p = new Post { Title = (string)json["title"], content = (string)json["content"] }; 
     db.Posts.Add(p); 
     db.SaveChanges(); 
     return Ok(); 
    } 

不过,我不相信这是最好的做法,因为第一次我送的一切作为一个字符串解析它,但也因为如果我的标题或内容项目有一个'字符,然后程序错误了。我想知道什么是最好的方法来做到这一点。我相信另一种方法是将我的模型作为参数传递给我的方法,但我想知道除此之外是否还有其他方法可以做到这一点。就像我说的,这不是一个非常具体的问题,我只是想知道最佳实践。 (一些代码备份你的回应将不胜感激)

谢谢!

回答

0

您应该允许JSON.Net做反序列化你的pipleline,而不是你的方法。此外,刚刚发布对象本身,而不是建立了一个JSON字符串

$scope.submit = function() { 
    $http.post("/post/new", $scope.form). 
     success(function (data, status, headers, config) { 
      console.log("Success") 
      $location.path("/news"); 
     }).error(function (data, status, headers, config) { 
      console.log("Error"); 
     }); 
}; 

[HttpPost][Route("New")] 
public IHttpActionResult New([FromBody] Post input) 
{ 
    db.Posts.Add(input); 
    db.SaveChanges(); 
    return Ok(); 
}