Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HOW TO MAKE create var array dynamic in C#

Tags:

c#

ajax

In my controller I'm using following code to return the 2 lists to ajax request:

public JsonResult getdata(int seat_plane_id)
{
    int lid;
    layoutsController L = new layoutsController();
    JsonResult result = L.getlayouts(seat_plane_id);
    List<layouts> L1 = (List<layouts>)result.Data;
    List<SeatPlans>[] allUser = new List<SeatPlans>[2];
    for(int i=0; i<L1.Count; i++)   
    {
        String lid1 = L1[i].ticket_no_start;
        lid = Int32.Parse(lid1);
        allUser[i]= new List<SeatPlans>();
        allUser[i]= db.SEATPLAN.Where(d => d.layout_id == lid).ToList();
    }

    var v = new { allUser0 = allUser[0], allUser1 = allUser[1] ,allUser2= allUser[2] };
    return Json(v, JsonRequestBehavior.AllowGet);
}

I'm catching the returned value in ajax request as:

success: function (v) {
       loadData(v.allUser0);
       loadData(v.allUser0);
    }

But my problem is: I will have a dynamic size of allUser (size is L1.Count). And so I will get L1.Count no of lists. So I need to create var v={ } dynamically. How to do this? If you have any other solution, it is acceptable.

like image 631
rakshithrai Avatar asked Jun 06 '26 06:06

rakshithrai


1 Answers

Simply make v a dictionary. The serializer will generate identical JSON for you as you would have had with the dynamic object.

var v = new Dictionary<string, SeatPlans>();

int id = 0;
foreach (SeatPlans sp in allUser)
{
    v.Add($"allUser{id}", sp);
    id++;
}

return Json(v, JsonRequestBehavior.AllowGet);
like image 117
Patrick Hofman Avatar answered Jun 07 '26 20:06

Patrick Hofman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!