如何将列表从aspx传递给javascript?

时间:2010-08-05 14:14:25

标签: c# .net javascript asp.net-mvc

我有一个列表,我循环填充我的表。我想将一行数据传递给我的javascript代码。如果没有,我想传递列表和ID号以在列表中搜索该行。我怎样才能做到这一点?

<%foreach(var item in Model.NewList) { %>
<tr>
   <td><%=item.EntryDate.ToShortDateString() %></td>
   <td onmouseover="showDetailsHover(<%=item %>,<%=item.idNumber%>);" 
       onmouseout="hideDetailsHover();"><%=Html.ActionLink(item.idNumber,"SummaryRedirect/" + item.idNumber) %></td>
</tr>
<% } %> 

4 个答案:

答案 0 :(得分:1)

您可以使用Json序列化来传递此数据 http://json.codeplex.com/ - 序列化库

答案 1 :(得分:1)

“将列表从aspx传递到javascript”的概念有点难以理解,因为ASP.NET代码在服务器上运行,javascript代码在浏览器中运行。因为它们存在于不同的域中,所以不能简单地将列表从一个域“传递”到另一个域。

但是,您有几种选择:

  • 公开您可以从javascript访问的网络服务。 Web服务可以负责提供数据行,以便javascript可以理解它。
  • 当您的网页加载时,将静态格式化的JSON数据直接放入您的javascript函数中。 JSON是javascript可以理解的格式。虽然从技术上讲,这不是将一个变量“传递”到ASP.NET的javascript函数中,但是它说“这是我想在javascript函数中运行的数据/当它在客户端运行时。”

答案 2 :(得分:1)

我能想到的最快的方法是:

  1. 使用Json.Net将您的列表序列化为页面上的json字符串。
  2. 包含jQueryjQuery-json插件。
  3. 在javascript函数中定义javascript列表。
  4. 在你的aspx页面上有这样的东西:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://jquery-json.googlecode.com/files/jquery.json-2.2.js"></script>
    <script type="text/javascript">
        function foo() {
            // This is where we use the Json.Net library
            var rawJsonString = '<%= Newtonsoft.Json.JsonConvert.SerializeObject(Model.NewList) %>';
    
            // This is where we use the jQuery and jQuery-json plugin
            var list = $.evalJSON(rawJsonString);
    
            // Do stuff with your list here
        }
    </script>
    

答案 3 :(得分:0)

感谢这些想法。我最终挖掘了你的建议,我在列表中使用了for循环,然后根据循环将数据添加到行中...

success: function(data) {
        var loopList = data.message.NewList;
        for (var i = 0; i < loopList.length; i++) {
            addRecentData(loopList[i]);
        }
    },
});
function addRecentData(data) {
    ....
}

轻推的感觉!