如何从控制器端发布数组并使用angularjs mvc c#?

时间:2017-04-12 11:01:49

标签: c# angularjs entity-framework

您好我正在为产品crud operation.i创建小型演示,有2个表Products和ProductItems。我想提交时间添加第一个产品表条目,然后在这个productid获取并添加到ProductItems但是如何使用实体框架做到这一点。我也使用http post方法传递ProductItems数组但是我没有得到服务器端总是得到0计数你能不能知道怎么做这个东西。我在这里展示我的实体,下面列出的方法。

这是我的产品实体:

[Table("Products")]
public class Products
{
    [Key]
    public int pid { get; set; }

    public string name { get; set; }

    public string description { get; set; }

    public string image_url {get;set;}
}

这是我的ProductItems实体:

    [Table("ProductItems ")]
    public class ProductItems 
   {
    [Key]
    public int id { get; set; }

    [ForeignKey("Products")]
    public int pid {get; set;}

    public int Qty { get; set; }

    public Decimal Rate { get; set; }

    public virtual Products Products { get; set; }
}

这是我的controller.js:

$scope.AddProduct = function () {
        var P =
            {                    
                name : $scope.ProductName,
                description : $scope.description,
                ProIList: $scope.ProItemslist,
                image_url : $scope.Image
            };        

                var GetData = PService.AddPro(P.image_url, P);
                GetData.then(function (msg) {

                }, function (err) {
                });

        }
    }

这是我的service.js

this.AddPro = function (file, P) {
    var formData = new FormData();
    formData.append("file", file);
    formData.append("name", P.name);
    formData.append("description", P.description);
    formData.append("ProIList", P.ProIList);  // this is array list      

    var Response = $http.post("/Product/AddProduct", formData,
        {
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
        })
    .success(function (res) {
        Response = res;
    })
    .error(function () {
    });
    return Response;
}

这是我的控制器方法:

[HttpPost]
    [Route("AddProduct")]
    public string AddProduct(string name, string description, IList<ProductItems> ProIList) // here i m not getting array 
    {
        Products objP = new Products();            
        string Res = "";

                    objP.name = name;
                    objP.description = description;                       
                    db.Promotions.Add(objP); // and here add product is done now want to add ProductItems table entry so how can do 
                   db.SaveChanges();                  
        return Res;
    }

所以这里我清楚所有列出方法类现在任何人都知道如何做到这一点然后请让我知道。

2 个答案:

答案 0 :(得分:0)

我通常发布的是创建一个对象,然后我将在$ http.post中传递。还要确保您要发布的对象结构在您的ProductItems上具有相同的结构。

在您的情况下,您应该有一个视图模型,以便在发布时不会出现问题

示例:

public class ProductsViewModel{
   public string name {get;set;}
   public string description {get;set;}
   public List<ProductItems> productList{get;set;}
}

api post call

[HttpPost]
[Route("AddProduct")]
public async Task<IHttpActionResult> PostAssessment(List<ProductsViewModel> model)
{
}

你的angularjs代码应该看起来像

var products=[
  {
    name: "Product 1"
    description: "prod description"
    productList: [
        {
          //put data of product list here
        }
     ]
}
];
var Response = $http.post("/Product/AddProduct", products,
    {
        headers: { 'Content-Type': 'application/json' }
    })
.success(function (res) {
})
.error(function () {
});

希望这会有所帮助

upate: 这个if if for image upload api

   [HttpPost]
    public async Task<IHttpActionResult> Post()
    {
        try
        {
            if (!Request.Content.IsMimeMultipartContent())
                 throw new 
                HttpResponseException(HttpStatusCode.UnsupportedMediaType);
         //do your upload functions here


         } catch(Exception e){

         }
     }
在angularjs中

使用ngFileUpload

 Upload.upload({
                    url: apiUrl + '/File',
                    data: { file: file },
                }).then(function (response) {
                    //the api should return the url of your image.
                     //you can now use the code above. add it to the object 
                    //then post it to addproducts
                });

答案 1 :(得分:0)

好的,这是一个使用ViewModel的理想场所。

我假设您要传递给Server的数据格式包含一个Name字段,一个Description字段和一个List的产品。

这就是你要在Client方代表的方式(而不是你曾经做过的)

var products= {
   name: "Product 1",
   description: "prod description",
   productList: [
    {
      //put data of product list here
    }
   ]
};

以及VM ViewModel

的形式
var clientSideVM = {
  Name: products.name,
  Description: products.description,
  Products: products.productList
};    

将其发布到Server

$http.post("AddProduct", clientSideVM)
   .then(function(response) { 
       // Access The Response Object
   }, function(error) {
       // Access The Error Object 
   });

//Server Side Code
//Exactly matching VM
public class CustomViewModel {
   public string Name { get; set; }
   public string Description { get; set; }
   public List<ProductItems> Products { get; set; }
}

[HttpPost, Route("AddProduct")]
public string AddProduct(CustomViewModel viewModel) {
  //here you have all you data from Client Side,
  var name = viewModel.Name;
  // Work on them here
  //Rest of your Code
}