【问题标题】:How pass int list from action to view, then from view to method in mvc 4?如何将 int 列表从动作传递到视图,然后从视图传递到 mvc 4 中的方法?
【发布时间】:2013-07-25 05:32:17
【问题描述】:

Create(post) 操作中的 MVC4 应用程序中,我想通过 int 类型列表 来查看是否发生错误。然后,从那里通过 ajax post 将其传递给同一控制器中的其他方法。所以,TempDataViewDataViewBag 不要帮助我。

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

return View(model); 之后,selectedItems 的列表传递给Create.cshtml 视图。我检查过它在这里有价值。但是从这里我应该通过 ajax 帖子将该列表传递给 GetTreeData 方法:

@{
   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"]
    });

MyController 中,在GetTreeData 方法中TempData["SelectedItems"]null

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

我对所有(TempData、ViewData 和 ViewBag)都进行了尝试。没有任何改变。

如何将该列表从操作传递到视图,然后从该视图传递到方法?

【问题讨论】:

  • 我找到了解决方案。首先,我将 int 列表转换为字符串列表为 "1,2,8",然后,url: "@Url.Action("GetTreeData", "MyController", new { param = stringList })",

标签: asp.net-mvc asp.net-mvc-4 asp.net-ajax viewbag tempdata


【解决方案1】:

创建一个视图模型,在该视图模型中将您现在使用的模型设置为一个字段,并为该列表添加一个额外的字段

【讨论】:

  • 是的,我没有其他办法。我找不到任何办法,就这样吧。
猜你喜欢
  • 1970-01-01
  • 2011-05-12
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-01
  • 2017-12-16
相关资源
最近更新 更多