【发布时间】:2016-02-04 19:16:49
【问题描述】:
我想在@Url.Action 中传递两个参数。
查看:
<select id="ddlSearchBy" name="ddlSearchBy" style="width: 150px">
<option value="TaxCode">Tax Code</option>
<option value="TaxDescription">Tax Description</option>
<option value="ClassDescription">Class Description</option>
<option value="ZoneName">Zone Name</option>
</select>
<input type="text" name="txtSearchValue" id="txtSearchValue"/>
<button type="button" id="btnDownload">Download</button>
<button type="button" id="btnSearch">Search</button>
单击下载按钮时,我在 Masters Controller 中调用方法“ExportToExcel”,还需要传递两个参数。即select html和文本框值的选定值。
现在,我正在使用如下;
<button type="button" id="btnDownload" onclick="location.href='@Url.Action("ExportToExcel", "Masters", new { ddlSearchBy = @TempData["ddlSearchBy"], txtSearchValue = @TempData["txtSearchValue"] })'">Download</button>
可以直接在@Url.Action中传递html控件值吗?
已编辑:
控制器:
[HttpPost]
public ActionResult ExportToExcel(string ddlSearchBy, string txtSearchValue)
{
var grid = new GridView();
grid.DataSource = from data in GetTaxMasterTable(ddlSearchBy, txtSearchValue)
select new
{
Code = data.taxCode,
TaxDescription = data.taxDescription,
ClassDescription = data.classDescription,
Location = data.locationShortName,
Zone = data.zoneName,
TaxValue = data.taxValue,
Tax = data.taxPercentage,
ModifiedDate = data.modifiedDate
};
grid.DataBind();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename = TaxMaster.xls");
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
return RedirectToAction("TaxMaster");
}
jQuery:
$("#btnSubmitDownloadExcel").click(function (e) {
var ddlSearchBy = $("#ddlSearchBy").val();
var txtSearchValue = $("#txtSearchValue").val();
$.ajax({
type: "POST",
url: "/Masters/ExportToExcel",
data: JSON.stringify({ "ddlSearchBy": ddlSearchBy, "txtSearchValue": txtSearchValue }),
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
alert(JSON.stringify(data));
},
error: function (data) {
alert("err");
alert(JSON.stringify(data));
}
});
});
此代码未下载 Excel。
【问题讨论】:
-
你需要 javascript/jquery 来更新
location.href的值(或者只是使用带有FormMethod.Get的表单) -
是的..我试过了,但我的场景不适合..
-
我需要在方法中下载一个excel,如果我使用Jquery ajax调用,它不会下载。但是如果我使用上述方法,它的下载。
-
不适合什么?使用 javascript 还是使用表单?
-
使用带有 method="get" 的表单。它会工作,就像使用常规超链接一样。
标签: html asp.net-mvc asp.net-mvc-4 location-href url.action