将复杂对象从window.open传递到MVC控制器

huangapple go评论75阅读模式
英文:

Pass a complex object from window.open to MVC Controller

问题

我正在处理将复杂数据从window.open()传递给MVC Controller操作方法参数的JavaScript功能。
我通过构建查询字符串并从控制器的[FromQuery]中检索它们成功实现了这一点。

但我的问题是,我想将数据传递为模型对象。在window.open()中是否可能?

以下是我的JavaScript代码:

$("#btnExportToExcelForBatch").on('click', function() {
    var currentBatchId = 0;
    var empName = $("#empName").val();
    var empId = $("#empId").val();
    var deptId = $("#deptId").val();
    window.open("/Download/ExportToExcel?EmpName=" + empName + "&EmpId=" + empId + "&DeptId=" + deptId);
});

如您所见,我可以将数据传递到URL中,但似乎会暴露出来。那么,有没有办法我可以传递它们如下:

var url = @Url.Action("ExportToExcel", "Download");

但我无法将它们传递。是否有可能通过模型对象发送到MVC控制器来实现?

public async Task<IActionResult> ExportToExcel(EmployeeModel employeeModel)
{
    // 一些代码
    return File();
}

有人能帮我解决这个问题吗?

英文:

I am working on a javascript functionality of passing complex data from window.open() to MVC Controller action method parameter.
I was able to achieve it by constructing a query string and retrieving them from [FromQuery] in controller.

But my problem is I want to pass the data as a model object. Is it possible in window.open()

Below is my javascript code

$(&quot;#btnExportToExcelForBatch&quot;).on(&#39;click&#39;,
                function() {
                    var currentBatchId = 0;
                    var empName = $(&quot;#empName&quot;).val();
                    var empId = $(&quot;#empId&quot;).val();
                    var deptId = $(&quot;#deptId&quot;).val();
					window.open(&quot;/Download/ExportToExcel?EmpName=&quot;
                        + empName + &quot;&amp;EmpId=&quot; + empId + &quot;&amp;DeptId=&quot;
                        + deptId);                 
                });

As you can see, I can pass the data in the URL, but it seems to be exposed. So, is there way that I can pass in
<br/>
var url = @Url.Action(&quot;ExportToExcel&quot;, &quot;Download&quot;);

But I am unable to pass them.

Is there a possible way to achieve by sending as model object to MVC controller.

public async Task&lt;IActionResult&gt; ExportToExcel(EmployeeModel employeeModel)
{
     // SomeCode
     return File();
}

Could anyone help me with this problem

答案1

得分: 1

// 生成查询字符串并使用window.open打开
var urlquerstr = BaseUrl + "/Download/ExportToExcel?EmpName=" + empName + "&EmpId=" + empId + "&DeptId=" + deptId;

// 使用Url.Action的等效方式
var urlquerstr = "@Url.Action("ExportToExcel", "Download", new { EmpName= Model.empName, EmpId= Model.empId, DeptId=Model.deptId })";

// 打开链接
window.open(urlquerstr);

// 或者使用AJAX进行POST请求
$("#btnExportToExcelForBatch").on('click', function() {
    var currentBatchId = 0;
    var empName = $("#empName").val();
    var empId = $("#empId").val();
    var deptId = $("#deptId").val();
    // 生成要发送到控制器的数据
    var json = { EmpName: empName, EmpId: empId, DeptId: deptId };
    $.ajax({
        url: '@Url.Action("ExportToExcel", "Download")',
        type: 'post',
        dataType: "json",
        data: { "json": JSON.stringify(json) },
        success: function(result) {
            alert(result);
            //window.open(result);
        },
        error: function(error) {
            console.log(error)
        }
    });
});

// 控制器方法示例
[HttpPost]
public async Task<IActionResult> ExportToExcel(string json)
{
    var serializer = new JavaScriptSerializer();
    dynamic jsondata = serializer.Deserialize(json, typeof(object));

    // 从AJAX调用中获取变量
    var EmpName = jsondata["EmpName"];
    var EmpId = jsondata["EmpId"];
    var DeptId = jsondata["DeptId"];

    // 在这里处理变量

    return Json("File exported successfully");
}

// 如果要在JavaScript参数中使用URL.Action
'@Url.Action("ExportToExcel", "Download")?EmpName=' + empName + '&EmpId=' + empId + '&DeptId=' + deptId;
英文:

Okay, you have couple of options here. You can either generate the query string and then send it to window.open but your parameters would be exposed in this case:

var urlquerstr = BaseUrl + &quot;/Download/ExportToExcel?EmpName=&quot;+ empName + &quot;&amp;EmpId=&quot; + empId+ &quot;&amp;DeptId=&quot;+ deptId;

Equivalent using Url.Action:

var urlquerstr = @Url.Action(&quot;ExportToExcel&quot;, &quot;Download&quot;, new { EmpName= Model.empName, EmpId= Model.empId, DeptId=Model.deptId })

Once you have generated your query string, then you can simply do:

window.open(urlquerstr);

OR you are looking to POST your parameters to your Controller method and based on that take an appropriate action. You can do this using AJAX. Specific to your case:

$(&quot;#btnExportToExcelForBatch&quot;).on(&#39;click&#39;,
function() {
var currentBatchId = 0;
var empName = $(&quot;#empName&quot;).val();
var empId = $(&quot;#empId&quot;).val();
var deptId = $(&quot;#deptId&quot;).val();
//Generate data to be sent to the controller
var json= { EmpName: empName , EmpId: empId , DeptId: deptId };
$.ajax({
url: &#39;@Url.Action(&quot;ExportToExcel&quot;, &quot;Download&quot;)&#39;,
type: &#39;post&#39;,
dataType: &quot;json&quot;,
data: { &quot;json&quot;: JSON.stringify(json)},
success: function (result) {
alert(result);
//window.open(result);
},
error: function (error) {
console.log(error)
}
});                
});

And your Controller method would look like:

using System.Web.Script.Serialization;
[HttpPost]    
public async Task&lt;IActionResult&gt; ExportToExcel(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var EmpName= jsondata[&quot;EmpName&quot;];
var EmpId=jsondata[&quot;EmpId&quot;];
var DeptId=jsondata[&quot;DeptId&quot;];
//Do something with your variables here    
return Json(&quot;File exported successfully&quot;);
}

If you want to use URL.Action with Javascript parameters:

&#39;@Url.Action(&quot;ExportToExcel&quot;, &quot;Download&quot;)?EmpName=&#39; + empName + &#39;&amp;EmpId=&#39; + empId &#39;&amp;DeptId=&#39; + deptId;

Please note that you would have to call this in a javascript function.

答案2

得分: 0

你需要在访问 /Download/ExportToExcel 时将 employeeModel 参数值作为 JSON 主体传递。

问题在于必须使用 POST 或 PUSH 操作来将 JSON 参数值传递到请求主体中,以使用 ExportToExcel 方法。

请查看 此答案 获取详细信息。

英文:

You have to put employeeModel parameter value as json body when accessing the /Download/ExportToExcel

The problem is that ExportToExcel method must be used with POST or PUSH action to pass the Json parameter value in the request body.

Please check this answer for details

huangapple
  • 本文由 发表于 2020年1月6日 18:53:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610796.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定