ASP.NET MVC:将复杂数据从View传递给Controller

时间:2014-02-04 14:29:13

标签: .net asp.net-mvc-4 actionlink

我有一个Controller,它生成以下对象并通过ViewBag将其传递给View:

public class ObjectList
{
  public ObjectItem[] Item { get; set; }
}


public class ObjectItem
{
  public string Name { get; set; }
  public decimal Value1 { get; set; }
  public decimal Value2 { get; set; }
}

在视图中,此数据显示在表格中。吹桌子我有一个ActionLink,它应该将所有数据传递回Controller进行进一步处理。我怎样才能做到这一点。 ActionLink是正确的选择,它可以是List中的数百个OjectItem。对此还有其他方法吗?

我希望你能帮助我。

3 个答案:

答案 0 :(得分:0)

不确定是否有办法使用MVC,但我通常做的是使用jquery遍历表中的项目,将其推送到javascript数组,然后在发出请求时将数组作为参数传递MVC控制器。

例如:

// Javascript variable that will contain the values
var selectedPositionNumbers = new Array();

// In my case, i store the value of the row when user click a checkbox in the same row
$('body').on('click', 'input[id*="IsSelected"]', function () {
            var positionNr = $(this).attr('id').split("IsSelected")[1];
            var isChecked = $(this).is(':checked');
            if (isChecked) {
                if ($.inArray(positionNr, selectedPositionNumbers) == -1) {
                    selectedPositionNumbers.push(positionNr);
                }
            }
        });

// And later on when making the request
$.ajax({
        url: '@Url.Action("SendSelectedValues")',
        data: JSON.stringify({ positionNrList: selectedPositionNumbers }),
        type: 'post',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            // Completed statement here
        }
    });

在我的情况下,我只需要存储一个值,所以我只需要创建一个字符串数组,但对于您的情况,也许这篇文章提供了一个更好的示例:http://abiyh.blogspot.nl/2011/01/posting-javascript-array-using-jquery.html

答案 1 :(得分:0)

如果信息具有任何关键值,我肯定会在服务器(数据库,文件系统等)上保存它的副本,并让ActionLink将某种ID提交回服务器以帮助检索它。您需要清除“未使用的”数据(例如,从未导出过并且不再需要),但根据您的情况,可能比使用您认为已发送的数据冒用户风险更安全。

答案 2 :(得分:0)

我认为你应该将数据存储在会话中。当操作链接回发时,您只需获取存储在会话中的数据版本。

与@JTMon提供的答案一样,如果您使用操作链接将数据发送回服务器,则必须验证所有数据(因为它现在是用户输入并且可能已被篡改)。您可以使用CRC或HMAC检查等机制。