简体   繁体   English

如何将字典从Java Script Angular客户端传递到MVC3服务器

[英]How to pass a dictionary from Java Script Angular client to MVC3 server

Trying to pass a dictionary from JS to MVC with no success. 试图将字典从JS传递到MVC失败。 The data (reportIdAndStatus in mvc controller) is null. 数据(mvc控制器中的reportIdAndStatus)为空。

I'm using angular $resource and MVC 3. Thanks. 我正在使用angular $ resource和MVC3。谢谢。

Angular Controller: 角度控制器:

var reportStatusdictionary = {};
//build a dictionary
            for (var x = 0; x < reports.length; x++) {
                reportStatusdictionary[reports[x].Id] = reports[x].StatusId
            }

reportsService.getReportStatusComment({ reportStatusdictionary: reportStatusdictionary }

Angular Resource Definition: 角资源定义:

 getReportStatusComment:
        {
            method: 'GET',
            params: { reportIdAndStatus: '@reportIdAndStatus', command: 'GetReportStatusComment' },
            isArray: false
        }

MCV Controller: MCV控制器:

    [HttpGet]
    public string GetReportStatusComment(Dictionary<Guid, int> reportIdAndStatus)

Request In Browser: 在浏览器中请求:

在此处输入图片说明

Instead of dictionary,I'd recommend creating a view model for simplicity and ease of debugging purposes. 为了简化和方便调试,我建议创建一个视图模型而不是字典。 You can do as below: 您可以执行以下操作:

  1. Create view model like below: 创建如下的视图模型:

      public class ReportViewModel { public Guid Id{get;set;} public int StatusId{get;set;} } 
  2. Then your controller will look like 然后您的控制器将看起来像

     [HttpGet] public string GetReportStatusComment(IEnumerable<ReportViewModel> reportViewModel) 
  3. Then your get url will be 然后您的获取网址将是

    http://localhost:53854/report/getreportstatuscomment?[0].id=guidValue1&[0].StatusId=1&[1].id=guidValue2&[1].StatusId=2

    You can easilty construct the url structure like this in your JavaScript Code. 您可以像这样在JavaScript代码中轻松构建url结构。 You can read more on model binding at @Darin Dimitrov's answer , Phil Haack's blog post and MSDN magazine article . 您可以在@Darin Dimitrov的答案Phil Haack的博客文章MSDN杂志的文章中阅读有关模型绑定的更多信息

Update 更新

If you don't want to build that url structure then you can send JSON to server. 如果您不想构建该URL结构,则可以将JSON发送到服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM