将View中的JavaScript数组传递给Controller Razor

时间:2014-06-24 22:27:50

标签: jquery asp.net-mvc asp.net-mvc-4 razor

我需要将一个数组从我的视图传递给Action,怎么做?我读了几篇博客和Q& A,没有运气。以下是我的代码。我需要在“CreateScoreLinkFile”中获取“selectedVals”。

提前致谢。

<script>
    $('#btnGetFile').on('click', function () {  
      var selectedVals = ["12","233","121","34","34"];

     location.href = '@Url.Action("CreateScoreLinkFile", "Home"';                             

    });          
</script>


    public FileStreamResult CreateScoreLinkFile()
    {          

        EDMGreDataIO objPDMDataIOForGADIReports = new EDMGreDataIO();
        string scoreLinkData = objPDMDataIOForGADIReports.GetScoreLinkReport(104488, 3582527, 2, "10-JUL-2009", "01-JUL-2009", 1);           

        var byteArray = Encoding.ASCII.GetBytes(scoreLinkData);
        var stream = new MemoryStream(byteArray);
        string sFileName = "ScoreReport " + DateTime.Now.ToString("ddd dd MMMM yyyy hh:mm:ss tt") + ".txt";
        return File(stream, "text/plain", sFileName);
    }

2 个答案:

答案 0 :(得分:1)

由于您正在发出GET请求,因此可以将值作为查询字符串参数传递,这些参数可以在控制器操作中接收

 <script>
    $('#btnGetFile').on('click', function () {
        var baseUrl = '@Url.Action("CreateScoreLinkFile", "Home")';
        var selectedVals = ["12", "233", "121", "34", "34"];

        location.href = baseUrl + "?selectedVals=" + selectedVals;

    });
</script>

public FileStreamResult CreateScoreLinkFile(string selectedVals)
    {  
        //you can use any serialzer to deserialize your string to an array
        string[] arrSelectedVals = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(selectedVals);
        EDMGreDataIO objPDMDataIOForGADIReports = new EDMGreDataIO();
        string scoreLinkData = objPDMDataIOForGADIReports.GetScoreLinkReport(104488, 3582527, 2, "10-JUL-2009", "01-JUL-2009", 1);           

        var byteArray = Encoding.ASCII.GetBytes(scoreLinkData);
        var stream = new MemoryStream(byteArray);
        string sFileName = "ScoreReport " + DateTime.Now.ToString("ddd dd MMMM yyyy hh:mm:ss tt") + ".txt";
        return File(stream, "text/plain", sFileName);
    }

答案 1 :(得分:0)

我点击了按钮

,如下所示
            var exportForm = document.forms[0];
            exportForm.selectedValue.value = selectedVals;
            exportForm.target = "_blank";
            exportForm.action = '@Url.Action("CreateScoreLinkFile", "Home")';
            exportForm.submit();