简体   繁体   English

在asp.net中调用url.action时,模型为null

[英]Model is null when url.action is called in asp.net

My model have List products which get from database. 我的模型具有从数据库中获取的列表产品。 When index view loaded, i get the variable from input of user, then model get varible, and return view OutputTableAsync. 加载索引视图时,我从用户输入中获取变量,然后模型获取变量,然后返回视图OutputTableAsync。 After view loaded, i click link "Export Excel", in debug mode, List products is null. 视图加载后,我单击链接“导出Excel”,在调试模式下,列表产品为空。

My view: 我的观点:

<body>
    @if (Model != null)
    {
        var products = Model.products.Products;
        <a href="@Url.Action("ExportToExcel","Home", new {products = products })">Export Excel</a>
        <table border="1" style="width: 100%">
            <thead>
                <tr>
                    <th>Model</th>
                    <th>Price</th>
                    <th>Link</th>
                    <th>ImageUrl</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var product in Model.products.SortProduct())
                {
                    <tr id="i">
                        <td align="center">@product.Model</td>
                        <td align="center">@product.FormatPrice()</td>
                        <td align="center"><a href="@product.Link">@product.Link</a></td>
                        <td align="center"><img src="@product.ImageUrl" style="width : 200px; height:200px ;" id="@product.ImageUrl" /></td>
                    </tr>
                }
            </tbody>
        </table>
    }
</body>

ExportToExcel method in controller: 控制器中的ExportToExcel方法:

public void ExportToExcel(List<Product> products)
{
    ExcelPackage pck = new ExcelPackage();
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Products");
    ws.Cells["A1"].Value = "Model";
    ws.Cells["B1"].Value = "Price";
    ws.Cells["C1"].Value = "Link";
    ws.Cells["D1"].Value = "ImageLink";
    int rowstart = 2;
    foreach(var item in products)
    {
        ws.Cells[string.Format("A{0}", rowstart)].Value = item.Model;
        ws.Cells[string.Format("B{0}", rowstart)].Value = item.Price;
        ws.Cells[string.Format("C{0}", rowstart)].Value = item.Link;
        ws.Cells[string.Format("D{0}", rowstart)].Value = item.ImageUrl;
        rowstart++;
    }
    ws.Cells["A:AZ"].AutoFitColumns();
    Response.Clear();
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment: filename=" + "ExcelFile.xlsx");
    Response.BinaryWrite(pck.GetAsByteArray());
    Response.End();
}

According to accepted answer here you can not pass complex type through Url.Action 根据此处接受的答案您不能通过Url.Action传递复杂类型

I would pass serialized version of object in this situation. 在这种情况下,我将传递对象的序列化版本。

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

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