【问题标题】:Passing ViewBag (has list of int type) to Controller将 ViewBag(具有 int 类型列表)传递给 Controller
【发布时间】:2015-06-17 15:18:20
【问题描述】:

我试图在 jquery 加载时将 int 类型列表传递给 Controller,但没有成功。 这是我的代码:

function Addcov() {
    var dt = '@ViewBag.dt';
    @{
        List<int> covtypes = new List<int>();
        foreach (var item in ViewBag.CovTypes)
        {
            covtypes.Add(item);
        }
    }
    alert('@covtypes');

    $("#Form").dialog({
         autoOpen: true,
         width: 1000,
         resizable: false,
         title: 'Add',
         modal: true,
         open: function () {
             $(this).load(
                 '../controller/AddAction', 
                 { fromDate: dt, CovTypes: JSON.stringify('@covtypes') },
                 function (response, status, xhr) {});
             },
             buttons: {}
        });
    }

【问题讨论】:

  • 那有什么问题?
  • 您将 Razor 代码(服务器端)与 javascript(客户端)混淆了。两者不直接互动。您使用 Razor 生成 javascript -- 查看呈现页面的源代码以查看将运行的代码。这是pass the list to javascript的方法。

标签: c# jquery asp.net-mvc jquery-ui-dialog


【解决方案1】:

我可能会看到您的问题,路径。调试并确保您传递的路径是正确的,并且数据实际上是通过 covtypes 传递的。

我在这里看到的主要问题是路径未正确传递。 尝试使用完整路径,看看会发生什么。

【讨论】:

  • 路径正确,发布到 'fromDate' 的数据有效,但是,'covtypes' 发布为 -- System.[List.Int32 ...但不是实际列表
  • 当然!因为您的列表是 List covtypes = new List();列表里面没有数据它有一个int!所以列表包含 System.[List.Int32] 的数据。您需要传递您的值而不是 int。编辑:请注意,您还对“@covtypes”进行了字符串化,因此 json 可以看到列表,但不会查看 foreach 值。所以你得到回报:System.[List.Int32]
【解决方案2】:

如果您在控制器上编写了调用方法会很有帮助,但在您的情况下,您发送的是 Get 请求,因此,您可能会指出该值来自 URI,如下所示:

public ActionResult AddAction(object fromDate, [FromUri] List<int> arr)

【讨论】:

    【解决方案3】:

    我可以建议将 ViewBag [List of int] 的值作为 csv 放在 html 元素中,然后将它们转换为 int 数组并传递给控制器​​

    <input type="hidden" id="list" value="@ViewBag.CovTypes.Aggregate((x,y)=>x+","+y)" />
    
    function Addcov() {
     var data=$("#list").val().split(",")map(function(i,e){   return parseInt(e);          });
    
    $("#Form").dialog({
         autoOpen: true,
         width: 1000,
         resizable: false,
         title: 'Add',
         modal: true,
         open: function () {
             $(this).load(
                 '../controller/AddAction', 
                 { fromDate: dt, CovTypes:JSON.stringify(data) },
                 function (response, status, xhr) {});
             },
             buttons: {}
        });
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多