how can i pass an array in window.location without ajax call

时间:2017-12-18 05:52:31

标签: javascript c# jquery asp.net-mvc

I want to send list array in ExportTo Method, but in ExportTo method student parameter get null value. If I use ajax it will work fine. But have to use window.locatoin for pass list array.

View

            $(document).ready(function () {

            $("#SaveBtn").click(function () {

                var student = {

                    Name: "Tanzid",
                    Department: "CSE"

                };
                var student1 = {

                    Name: "Yasir",
                    Department: "BBA"

                };
                var list = [];

                list.push(student);
                list.push(student1);

               var url = '@Url.Action("ExportTo", "Students")';

               var a = JSON.stringify(list);

               window.location = url + '?' + a;
            });
        })

.
Controller

Public void ExportTo(List<Student> student)
    {




    }

1 个答案:

答案 0 :(得分:0)

Iv'e tested some scenario of your problem and its work without using ajax:

Commented first your code coz i don't have it.

From Index View:

@{
    ViewBag.Title = "Index";
}
<script src="~/scripts/jquery-1.10.2.js"></script>
<h2>Index</h2>
<script>


     $(document).ready(function () {

    var person = [];
    person.push("Reign");//change like $("#idname").val();
    person.push("John");
    var listOfObjects = [];
    person.forEach(function (names) {
        var singleObj = {}
        singleObj['name'] = names;
        singleObj['dept'] = 'IT Dept.';
        listOfObjects.push(singleObj);
    });

    var url = '@Url.Action("Sample", "Home")';

    window.location = url + '?id=' + JSON.stringify(listOfObjects);
})

HomeController:

 public ActionResult Sample()
    {
       string getval = Request.QueryString["id"];
       string concat = @"{""data"":" + getval + "}";


        ValList vl = new JavaScriptSerializer().Deserialize<ValList>(concat);

        foreach (var item in vl.data)
        {
            Console.WriteLine("dept: {0}, name: {1}", item.dept, item.name);
        }

        return View();
    }


    public class ValList
    {

        public List<Values> data { get; set; }
    }

    public class Values
    {
        public string name { get; set; }
        public string dept { get; set; }
    }

It's all working its just depend on your project code with this:

        //var List = [];
        //var a = {
        //    Name: $("#").val(),
        //    Dept: $("#").val()
        //};
        //List.Push(a);

This is all i got..

It's Tested according to your needs.. Good Luck