How can I pass an object from my view to my controller in ASP.NET MVC?

Viewed 102

I want to download an Excel file when the user clicks on an Excel button. This is my Model and Object:

List<VMStockScreenerModel> listofStockScreener = (List<VMStockScreenerModel>)TempData["StockScreener"];
TempData["StockScreener"] = listofStockScreener;

This is the Excel button in my view:

<div class="col-md-1 padding-fx text-left" id="btn_FilterStocks">
    <span onclick="DownloadFilterStocks(@listofStockScreener.ToList());" class="pull-right icon-merge" data-toggle="tooltip" title="Download">
        <i class="fa fa-file-excel-o"></i>                        
        <i class="fa fa-cloud-download"></i>                 
    </span>                                                     
</div>

And here is my OnClick handler:

function DownloadFilterStocks() {
    debugger;
    var Obj = [@listofStockScreener];
    Obj = JSON.stringify({ 'Obj': Obj });
    var urls = '@(Html.Raw(Url.Action("Download_StockScreener","Home", new { Obj = "_Obj_"},Request.Url.Scheme)))'.replace("_Obj_", Obj);                   
}

Controller Code

public FileResult Download_StockScreener(VMStockScreenerModel Obj)
        {
            try
            {
                string fileName = string.Empty;
                string filePath = string.Empty;
                string fileName_filePath = string.Empty;


                fileName_filePath = StockScreener_DownloadExcel(Obj);
                if (fileName_filePath.Contains("@"))
                {
                    filePath = fileName_filePath.Split('@')[0];
                    fileName = fileName_filePath.Split('@')[1];
                }
                if (fileName != "")
                {
                    //return File(filePath, "text/csv", fileName);

                }

                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                Log.Logging("HomeController => Download_StockScreener", ex.Message + "\n" + ex.StackTrace);

            } return null;
        }
1 Answers

Instead of writing the whole code for you, i hope i can guide you to the answer by suggesting you the steps you need to take for making your solution work:

  1. Instead of span, make the element an anchor a.
  2. Render the anchor's URL server side (MVC view) without the query string part. Example: <a href="www.mydomain.com/Stocks/ExportToExcel" onclick="DownloadFilterStocks(this)">Export</a>
  3. In the anchor's click event, do the following:
    function DownloadFilterStocks(elem) {
        debugger;
        var Obj = [@listofStockScreener];

        var $elem = $(elem);

        //this converts JS object to query string
        var qParams = $.param(Obj); 

        //append query string to the anchor's base url
        var newUrl = $elem.attr('href') + '?' + qParams; 

        //assign new url
        $elem.attr('href', newUrl);
    }

The way this will work is:

  1. When the export link is clicked, JS code will be executed before server-side execution.
  2. JS will update the URL/href with the query string
  3. Server-side code will be executed with the new URL

Hope that helps you out. I ended up writing few codes anyway.

Note: My answer assumes that your server-side code is a working code.

Related