-1

We know that we can pass js variable value to mvc action but how could i pass js array to mvc action ?

So my question is how could i pass js array to mvc action by @Url.Action() ?

please see my sample code

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

my mvc action will download pdf at client and that is why i use

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

please guide me.

1
  • You method is marked [HttpPost] - you cannot navigate to a POST method (you need to submit a form). And if it was a GET method, then the url need to be ../DoSomething?id=10&deptno=C001&PdfInputs[0].firstName=John&PdfInputs[0].lastName=Doe&PdfInputs[0].age=46&PdfInputs[0].firstName=xxx....... but you would likely exceed the query string limit and throw an exception if you did that Commented Sep 24, 2018 at 22:18

2 Answers 2

2

Actually you can pass JSON string from array with @Url.Action() helper using query string parameter like this:

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

However I strongly discourage this practice because passed JSON string may exceeds query string limit if the array has large amount of data. Additionally, you cannot use @Url.Action() helper for action method marked with [HttpPost] attribute (it only works for GET method), hence I recommend to use jQuery.ajax() to pass PdfInputs array as List<PdfInputs> & TempData/Session state variable to store file contents, then download PDF file using HttpGet controller action as provided below:

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>

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

Controller (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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Click on this fiddle https://dotnetfiddle.net/RRwK1K

View

@{
    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>

Controller

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

1 Comment

@KendoStarter I changed my post and added a fiddle you can click on. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.