使用AngularJS将对象作为参数从View发送到Asp.net控制器

时间:2016-06-11 16:39:13

标签: asp.net angularjs

我试图将类别对象作为我的子类别对象的参数传递给我的Asp.net控制器。但是.net控制器总是将我的子类别.SuperCategory对象设置为null。

这是我的SubCategoryobject:

public class SubCategory
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    [Required]
    public Category SuperCategory { get; set; }
}

这是我的Asp.net控制器:

 public void createSubCategory([FromBody]SubCategory subcategory)
    {
        System.Diagnostics.Debug.WriteLine("SuperCategoryName: " + subcategory.SuperCategory.Name);
    }

这是我的AngularJS功能:

$scope.savedataSubCategory = function (subcategory) {
    $http.post('/AAAngular/createSubCategory', { Name: subcategory.Name, SuperCategory: {Id: subcategory.SuperCategory.Id, Name: subcategory.SuperCategory.Name } })
    .then(function successCallback(response) {
        console.log(response);
    }
    , function errorCallback(response) {
        console.log(response);
    })
}

我的观点的一部分:

     <input type="text" class="form-control" data-ng-model="subcategory.Name">
     <select data-ng-model="subcategory.SuperCategory">
          <option ng-repeat="category in categories">{{category}}</option>
     </select>
     <input type="button" value="Save" data-ng-click="savedataSubCategory(subcategory)"/> 

正确加载类别,这是{{subcategory.SuperCategory}}:

{"Id":63,"Name":"TestCat"} 

{{subcategory}}显示为:

 {"SuperCategory":"{\"Id\":63,\"Name\":\"TestCat\"}"}

我认为这就是问题所在,因为反斜杠而无法解读这个问题。当我只尝试传递一个类别变量时,它可以工作,但我需要整个对象 当我只尝试传递类别名称时,这就是我的子类别的样子。

{"SuperCategory":{"Name":"TestCat"}}

1 个答案:

答案 0 :(得分:0)

首先,您需要构建您希望传递的子类别对象。

 var subCategory = {};
 subCategory.Name = subcategory.Name;
 subCategory.SuperCategory = {} //this is your nested object
 subCategory.SuperCategory.Id = <assign whatever>
 ... likewise fill other properties

完成后,您需要对发布方法进行一些修正。

    $http({  
        url: "route/createSubCategory",  //change with correct one
        dataType: 'json',  
        method: 'POST',  
        data: subCategory,  
        headers: { "Content-Type": "application/json" }  
     }).success(function (response) {  
        console.log(response); 
     })  
     .error(function (error) {  
          alert(error);  
     });  

在网络API方面,它应该看起来像

    [Route("createSubCategory")]  
    [HttpPost]  
    public string createSubCategory([FromBody] SubCategory subCategory)  
    {  
        return "output";  
    }

请注意你的情况下的返回类型,它不应该是void。根据你的需要返回相应的viewmodel或字符串。我也用HttpPost属性修饰了这个方法。

希望这有帮助。