【问题标题】:Passing a model from view back to controller to export as CSV将模型从视图传回控制器以导出为 CSV
【发布时间】:2013-12-09 16:47:03
【问题描述】:

我正在尝试制作可下载的 CSV。我遇到的问题是我很不确定如何正确地将数据从视图传递回控制器。

我想要的 CSV 中的所有数据都在 @Model.Table 中。问题是我不确定如何将这些数据正确地传递回我的控制器。请注意,在下面的 js 中,我尝试使用 csvData = @Model.Table.ToCsv() 来做到这一点。这非常失败,所以我不确定如何正确地做到这一点。

<div class="btn btn-default pull-right" id="dispoCSV">
    <i class="icon-file-alt"></i>
    Disposition Report</div>
<script>
    $("#dispoCSV").click(function () {
        var csvData = @Model.Table.ToCsv();
        $.post("Respondent/DownloadCSV", function (data) {
            csvData
            })
        });
</script>

当我通过这个障碍时,我想我可以很容易地确定如何让我的 DownloadCSV 方法将其转换为 csv。

【问题讨论】:

  • 您只需要一个表格并提交即可。看来您正在尝试在这里重新发明轮子。
  • 你是如何生成表格的?
  • 不幸的是这已经嵌套在一个表单中。
  • 另外,我正在使用传递给 model.table 的 json 生成表

标签: c# jquery asp.net-mvc csv razor


【解决方案1】:

我认为您不需要从视图转换为 CSV。您的控制器可以做到这一点。我会这样尝试:

型号:

public class YourModel {
    public YourDataType Table { get; set; }
}

查看:

@model YourModel

@using (Html.BeginForm("Submit", "YourController", FormMethod.Post)) {
    // Put your model properties in the form so that they get passed to the controller on form submit;
    // use @Html.HiddenFor if you want to hide them from being displayed.
    // Since your table property has nested properties, you probably need a custom editor template for this.
}

控制器:

public class YourController : Controller {

    // Include an action here to display your view

    [HttpPost]
    public ActionResult Submit(YourModel model) {
        var csvData = model.Table.ToCsv(); // assuming you have this method already since it's in your code above
        // Do something with the data and return a view
    }
}

【讨论】:

    【解决方案2】:

    您应该传递可用于生成数据的过滤条件,而不是将整个数据传回。在您的 Action 方法中,读取此条件并生成数据并以 CSV 格式将其发送回 UI。

    【讨论】:

    • 所以访问数据。显示在视图中。然后使用单击按钮再次返回控制器访问数据并放入 csv。在我看来,访问一次数据会更容易吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多