0

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

$("#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);                 
                });

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
var url = @Url.Action("ExportToExcel", "Download");

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<IActionResult> ExportToExcel(EmployeeModel employeeModel)
{
     // SomeCode
     return File();
}

Could anyone help me with this problem

tereško
  • 58,060
  • 25
  • 98
  • 150
Vijay
  • 745
  • 2
  • 9
  • 25

2 Answers2

1

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 + "/Download/ExportToExcel?EmpName="+ empName + "&EmpId=" + empId+ "&DeptId="+ deptId;

Equivalent using Url.Action:

var urlquerstr = @Url.Action("ExportToExcel", "Download", 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:

$("#btnExportToExcelForBatch").on('click',
   function() {
      var currentBatchId = 0;
      var empName = $("#empName").val();
      var empId = $("#empId").val();
      var deptId = $("#deptId").val();
      //Generate data to be sent to the controller
      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)
    }
  });                
});

And your Controller method would look like:

using System.Web.Script.Serialization;

[HttpPost]    
public async Task<IActionResult> ExportToExcel(string json)
{
    var serializer = new JavaScriptSerializer();
    dynamic jsondata = serializer.Deserialize(json, typeof(object));

    //Get your variables here from AJAX call
    var EmpName= jsondata["EmpName"];
    var EmpId=jsondata["EmpId"];
    var DeptId=jsondata["DeptId"];

    //Do something with your variables here    

    return Json("File exported successfully");
}

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

'@Url.Action("ExportToExcel", "Download")?EmpName=' + empName + '&EmpId=' + empId '&DeptId=' + deptId;

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

Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
  • Apologies for the delay in response. I've tried it using Url.Action(), but while giving object values, it is throwing error `empName is not in current context` – Vijay Jan 09 '20 at 05:49
  • @Vijay Sorry it should be `Model.empName` and similar for rest of the values. – Rahul Sharma Jan 09 '20 at 05:57
  • `empName,empId,deptId` aren't Model property, they are created in JS. So, if I keep `@Model.empName`, it throws error – Vijay Jan 09 '20 at 06:12
  • @Vijay Then you can either go the `AJAX` method (preferred) or you can send the parameters as shown in the updated answer. – Rahul Sharma Jan 09 '20 at 06:27
  • haven't tried using ajax. Will try and let you know – Vijay Jan 10 '20 at 05:28
0

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

oleksa
  • 3,688
  • 1
  • 29
  • 54