ASP.Net MVC: как я могу передать массив js в действие mvc с помощью @ Url.Action () - PullRequest
0 голосов
/ 24 сентября 2018

Мы знаем, что можем передать значение переменной js в действие mvc, но как я могу передать массив js в действие mvc?

Поэтому мой вопрос заключается в том, как я могу передать массив js в действие mvc с помощью @ Url.Action()?

пожалуйста, посмотрите мой пример кода

[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;

, пожалуйста, направьте меня.

Ответы [ 2 ]

0 голосов
/ 25 сентября 2018

На самом деле вы можете передать строку JSON из массива с помощью помощника @Url.Action(), используя параметр строки запроса, например:

<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<PdfInputs> & TempData / Session переменная состояния для хранения содержимого файла, затем загрузка файла PDF с использованием действия контроллера HttpGet, как указано ниже:

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 Action)

[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");
}

Контроллер (Download Action)

[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();
    }
}
0 голосов
/ 25 сентября 2018

Нажмите на эту скрипку 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();
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...