0

In MVC4 application in Create(post) action I want to pass int type list to view if error occur. And then, from there to pass it to other method in same controller with ajax post. So, TempData, ViewData and ViewBag don't help me.

public ActionResult Create(CreateModel model)
       {
             if(hasCustomError)
             {
                  List<int> selectedItems = new List<int>() { 1, 2, 8 }; //for example.
                  ViewBag.VB = selectedItems;

                  //ViewData["VD"] = selectedItems;
                  //TempData["TD"] = selectedItems;

                   return View(model);
             }

             return RedirectToAction("Index");
       }

After return View(model);, list of selectedItems passed to Create.cshtml view. It has value here I checked. But from here I should pass that list to GetTreeData method via ajax post:

@{
   if (ViewBag.VB != null)
      {
          TempData["SelectedItems"] = ViewBag.VB as List<int>;
      }
}


    $("#myTree").jstree({
        json_data: {
            "ajax": {
                url: "@Url.Action("GetTreeData", "MyController")",
                type: "POST",
                dataType: "json",
                contentType: "application/json charset=utf-8"
            }
        },
        checkbox: {
            real_checkboxes: true,
            checked_parent_open: true
        },
        plugins: ["themes", "json_data", "ui", "checkbox"]
    });

In the MyController, in GetTreeData method TempData["SelectedItems"] is null .

 public string GetTreeData()
        {
           List<int> selecteds = null;
           if (TempData["SelectedItems"] != null)
            {
                selecteds = TempData["SelectedItems"] as List<int>;
                TempData["SelectedItems"] = null;
            }
            ......................................
        }

I tried this for all (TempData, ViewData and ViewBag). nothing changed.

How can pass that list from action to view and then from that view to method?

Jeyhun Rahimov
  • 3,769
  • 6
  • 47
  • 90
  • I found solution. First I convert int list to string list as "1,2,8" and then, url: "@Url.Action("GetTreeData", "MyController", new { param = stringList })", – Jeyhun Rahimov Jul 25 '13 at 10:03

1 Answers1

1

Create a viewmodel, in that viewmodel set your model that you are using now as a field, and add an extra field for that list

Dylan Slabbinck
  • 846
  • 1
  • 16
  • 27