【问题标题】:Passing input parameters to controller method via Html.ActionLink通过 Html.ActionLink 将输入参数传递给控制器​​方法
【发布时间】:2013-08-06 20:49:42
【问题描述】:

当用户点击Html.ActionLink 时,我需要调用一个控制器方法,该方法将为用户下载csv 报告。我还需要将两个输入框中的值传递给这个控制器,这两个输入框将表示他们正在寻找的开始和结束日期范围。

目前我可以使用 jQuery 分配 Html.ActionLink 参数,但是它们不会将其返回给控制器。控制器方法中的两个参数都使用null 值进行实例化。

我也不能使用表单/提交方法,因为该方法已在此特定表单上使用,以允许用户在导出到 csv 之前查看请求的日期范围内的数据。

jQuery

$(document).ready(function() {
    $('#startDate').change(function () {
        $('a').attr('start', $(this).val());
    });

    $('#endDate').change(function () {
        $('a').attr('end', $(this).val());
    });
});

ASP MVC 3 视图

@using (Html.BeginForm())
{
    <div id="searchBox">
        @Html.TextBox("startDate", ViewBag.StartDate as string, new { placeholder = "   Start Date" })
        @Html.TextBox("endDate", ViewBag.EndDate as string, new { placeholder = "   End Date" })
        <input type="image" src="@Url.Content("~/Content/Images/Search.bmp")" alt="Search"  id="seachImage"/>
        <a href="#" style="padding-left: 30px;"></a>
    </div>
    <br />
    @Html.ActionLink("Export to Spreadsheet", "ExportToCsv", new { start = "" , end = ""} )
    <span class="error">
        @ViewBag.ErrorMessage
    </span>
}

控制器方法

    public void ExportToCsv(string start, string end)
    {

        var grid = new System.Web.UI.WebControls.GridView();

        var banks = (from b in db.AgentTransmission
                    where b.RecordStatus.Equals("C") &&
                          b.WelcomeLetter
                    select b)
                    .AsEnumerable()
                    .Select(x => new
                               {
                                   LastName = x.LastName,
                                   FirstName = x.FirstName,
                                   MiddleInitial = x.MiddleInitial,
                                   EffectiveDate = x.EffectiveDate,
                                   Status = x.displayStatus,
                                   Email = x.Email,
                                   Address1 = x.LocationStreet1,
                                   Address2 = x.LocationStreet2,
                                   City = x.LocationCity,
                                   State = x.LocationState,
                                   Zip = "'" + x.LocationZip,
                                   CreatedOn = x.CreatedDate
                               });


        grid.DataSource = banks.ToList();
        grid.DataBind();

        string style = @"<style> .textmode { mso-number-format:\@; } </style> ";

        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=WelcomeLetterOutput.xls");
        Response.ContentType = "application/excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        grid.RenderControl(htw);
        Response.Write(style);
        Response.Write(sw.ToString());
        Response.End();
    }

【问题讨论】:

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


    【解决方案1】:

    我认为问题在于链接没有“开始”或“结束”属性。所以$('a').attr('start', $(this).val()); 不会做任何事情。

    <a href="#" id="lnkExport">Export to Spreadsheet</a>
    
    $('#lnkExport').click(function (e){
     e.preventDefault();
     window.location = '/Home/ExportToCsv?start=' + $('#startDate').val() + '&end=' + $('#endDate').val();
    });
    

    【讨论】:

    • 谢谢!我使用'@Url.Action("ExportToCsv", "Agent")' 来获取 URL,但这正是我想要的。谢谢!
    【解决方案2】:

    我也不能使用已经在使用的表单/提交方法 在此特定表格上,以允许用户查看日期中的数据 导出到 csv 之前请求的范围。

    实际上,您可以在表单中有 2 个提交按钮,并且在您的 POST 控制器操作中知道单击了哪个按钮以便采取相应的行动。就这样:

    <button type="submit" name="btn" value="search">Search</button>
    <button type="submit" name="btn" value="export">Export to Spreadsheet</button>
    

    现在您的控制器操作可以采用btn 参数:

    [HttpPost]
    public ActionResult SomeAction(MyViewModel model, string btn)
    {
        if (btn == "search")
        {
            // The search button was clicked, so do whatever you were doing 
            // in your Search controller action
        }
        else if (btn == "export") 
        {
            // The "Export to Spreadsheet" button was clicked so do whatever you were
            // doing in the controller action bound to your ActionLink previously
        }
    
        ...
    }
    

    正如您所看到的,在这两种情况下,表单都提交给相同的控制器操作,您显然会从表单数据中获取视图模型,此外您还将知道单击了哪个按钮以采取适当的操作.所以现在你可以摆脱你可能编写的所有花哨的 javascript 和锚。即使用户禁用了 javascript,您的应用程序也能正常工作。它是简单的 HTML。

    注意:请记住,您在问题中显示和调用的 控制器方法 不是 ASP.NET MVC 中的标准内容。在 ASP.NET MVC 中,这些方法具有名称。 Tjeir 称为控制器操作,必须返回 ActionResults 而不是 void。另外,您似乎在 ASP.NET MVC 应用程序中使用var grid = new System.Web.UI.WebControls.GridView();,真的吗?

    【讨论】:

    • 这无疑是一个 hack,你有什么建议?
    • 使用 OpenXML SDK 生成您的 Excel 文件:microsoft.com/en-us/download/details.aspx?id=5124
    • 这是我们必须在部署之前在服务器上安装的东西,还是我只需要在本地机器上安装一次,然后将其添加到控制器?
    • 不,您不需要安装任何东西。这是您必须在应用程序中引用的程序集。
    猜你喜欢
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 2021-03-10
    • 1970-01-01
    相关资源
    最近更新 更多