【问题标题】:ASP.Net MVC: How could i pass js array to mvc action by @Url.Action()ASP.Net MVC:我如何通过@Url.Action() 将 js 数组传递给 mvc 动作
【发布时间】:2019-02-28 03:45:25
【问题描述】:

我们知道我们可以将 js 变量值传递给 mvc 动作,但是我如何将 js 数组传递给 mvc 动作?

所以我的问题是我如何通过 @Url.Action() 将 js 数组传递给 mvc 动作?

请看我的示例代码

[HttpPost]
public ActionResult DoSomething(string id, string deptno, list<PdfInputs> PdfInputs)
{
    // Some magic code here...
}

var id = "10";
var deptno = "C001";

var PdfInputs = [];
for(inti=0;i<=totalbol-1;i++)
{
    var PdfInput = {
    firstName: "John",
    lastName: "Doe",
    age: 46
    };
}
PdfInputs.push(BOLPdfInput);

location.href = '@Url.Action("DoSomething", "Customer")?id=' + id + '&deptno=' + deptno;

我的 mvc 操作将在客户端下载 pdf,这就是我使用的原因

location.href = '@Url.Action("DoSomething", "Customer")?id=' + id + '&deptno=' + deptno;

请指导我。

【问题讨论】:

  • 您的方法被标记为[HttpPost] - 您无法导航到 POST 方法(您需要提交表单)。如果它是一个 GET 方法,那么 url 需要是 ../DoSomething?id=10&amp;deptno=C001&amp;PdfInputs[0].firstName=John&amp;PdfInputs[0].lastName=Doe&amp;PdfInputs[0].age=46&amp;PdfInputs[0].firstName=xxx....... 但如果你这样做,你可能会超过查询字符串限制并抛出异常

标签: javascript asp.net-mvc


【解决方案1】:

点击这个小提琴https://dotnetfiddle.net/RRwK1K

查看

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Tut123</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#theButton").click(function () {
                var id = "10";
                var deptno = "C001";

                var PdfInputs = [];
                var i;
                for (i = 0; i <= 3; i++) {
                    PdfInputs.push({
                        firstName: "John",
                        lastName: "Doe",
                        age: 46
                    });

                }
                var json = JSON.stringify(PdfInputs);
                location.href = '@Url.Action("theActionPassArray", "Home")?json=' + json;
            })
        })
    </script>
</head>
<body>
    <input type="button" id="theButton" value="Go" />
    @*credit to https://stackoverflow.com/questions/15112055/passing-dynamic-javascript-values-using-url-action*@
    @if (ViewBag.Data != null)
    {
        <span>The data sent to the server was:</span>@ViewBag.Data
    }
</body>
</html>

控制器

public class PassArray
{
    public string firstName { get; set; }
    public string lasttName { get; set; }
    public string age { get; set; }
}

public class HomeController : Controller
{
    public ActionResult theActionPassArray(string json)
    {
        /turn json passed value into array
        //You need to get NewtonSoft.JSON
        PassArray[] arr = JsonConvert.DeserializeObject<PassArray[]>(json);
        //put breakpoint here
        ViewBag.Data = json;
        return View("Tut123");        }

    public ActionResult Tut123()
    {
        return View();
    }

【讨论】:

  • @KendoStarter 我更改了我的帖子并添加了一个您可以点击的小提琴。谢谢。
【解决方案2】:

实际上,您可以使用@Url.Action() helper 使用这样的查询字符串参数从数组中传递 JSON 字符串:

<script>
$(function() {
    var id = "10";
    var deptno = "C001";

    var PdfInputs = [];
    for (var i = 0; i < totalbol; i++)
    {
        PdfInputs.push({
            firstName: "John",
            lastName: "Doe",
            age: 46
        });
    }

    location.href = '@Url.Action("DoSomething", "Customer")?id=' + id + '&deptno=' + deptno + '&PdfInputs=' + JSON.stringify(PdfInputs);
})
</script>

但是我强烈反对这种做法,因为如果数组有大量数据,传递的 JSON 字符串可能会超过查询字符串限制。此外,您不能将@Url.Action() 助手用于标记为[HttpPost] 属性的操作方法(它仅适用于GET 方法),因此我建议使用jQuery.ajax()PdfInputs 数组作为List&lt;PdfInputs&gt; 和@987654329 传递@/Session 状态变量来存储文件内容,然后使用HttpGet 控制器操作下载 PDF 文件,如下所示:

jQuery

<script>
$(function() {
    var id = "10";
    var deptno = "C001";

    var PdfInputs = [];
    for (var i = 0; i < totalbol; i++)
    {
        PdfInputs.push({
            firstName: "John",
            lastName: "Doe",
            age: 46
        });
    }

    $('#buttonid').click(function () {
         $.ajax({
             type: 'POST',
             url: '@Url.Action("DoSomething", "Customer")',
             // traditional: true,
             data: $.param({ id: id, deptno: deptno, pdfInputs: PdfInputs }, true),
             success: function (result) {
                 location.href = '@Url.Action("Download", "ControllerName")?id=' + id;
             },
             error: function (err) {
                 // error handling
             }
         });
    });
})
</script>

控制器(DoSomething 动作)

[HttpPost]
public ActionResult DoSomething(string id, string deptno, List<PdfInputs> pdfInputs)
{
    // Some magic code here...

    // Save file to TempData or Session state
    byte[] fileContent = fileStreamInstance.ToArray();

    TempData["FileToDownload"] = fileContent;

    return Json("Success");
}

控制器(下载操作)

[HttpGet]
public ActionResult Download(string id)
{
    string fileName = "yourfilename.pdf";
    // other code here
    if (TempData["FileToDownload"] != null)
    {
        byte[] content = TempData["FileToDownload"] as byte[];
        return File(content, "application/pdf", fileName);
    }
    else
    {
        return new EmptyResult();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 2021-04-14
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    相关资源
    最近更新 更多