简体   繁体   English

将模型从视图传递回控制器以导出为CSV

[英]Passing a model from view back to controller to export as CSV

I am trying to make a downloadable CSV. 我正在尝试制作可下载的CSV。 The problem I am having is I am quite unsure how to properly pass the data from the view back over to the controller. 我遇到的问题是我不确定如何正确地将数据从视图传递回控制器。

All of my data I want in the CSV is inside @Model.Table. 我想要的CSV数据都在@ Model.Table内。 Problem is I am not sure how to pass over that data properly back into my controller. 问题是我不确定如何将这些数据正确传递回我的控制器。 Notice in my js below I try to do that using csvData = @Model.Table.ToCsv(). 请注意,在我下面的js中,我尝试使用csvData = @ Model.Table.ToCsv()来做到这一点。 This horribly fails so I am unsure how to properly do this. 这非常失败,因此我不确定如何正确执行此操作。

<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>

When I am pass this obstacle I think I can easily firgure our how to make my DownloadCSV method turn this into a csv. 当我渡过这个障碍时,我想我可以轻松地了解一下如何使我的DownloadCSV方法将其转换为csv。

I don't think you need to convert to CSV from the view. 我认为您无需从视图转换为CSV。 Your controller can do that. 您的控制器可以做到这一点。 I would try it like this: 我会这样尝试:

Model: 模型:

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

View: 视图:

@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.
}

Controller: 控制器:

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
    }
}

Instead of passing the entire data back, You should be passing the filter criteria which can be used to generate the data. 您应该传递可用于生成数据的筛选条件,而不是传递整个数据。 And in your Action method, Read this criteria and Produce the data and send it in CSV format back the UI. 在您的操作方法中,请阅读此条件并生成数据,然后以CSV格式将其发送回用户界面。

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

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