c# - 从 View 获取 List<ViewModel> 到 Controller

标签 c# asp.net-mvc-4

我有一个 View允许编辑 ListViewModel .代码一直工作到显示功能。但是我无法从 View 中获取同一个列表中的值。

        public ActionResult Funtion()
        {
            List<ViewModel> ViewModel= (List<ViewModel>)TempData["ViewModel"];
            return View(ViewModel);
        }

        [HttpPost]
        public ActionResult UserFormSubmission(List<ViewModel> ViewModel)
        {    
            return View();
        }        

POST 函数的List 中的值为null。 我怎样才能从 View 中获取值到 Controller 中。

编辑: 我尝试使用提到的解决方案来解决问题 How to pass IEnumerable list to controller in MVC including checkbox state? .但是遇到如下错误:

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable

我也无法理解其中某些标签的用法,比如 AntiForgeryToken , HiddenFor , ETC。 因此,如果可能的话,请有人提出一个简单的解决方案或更好的解释。

编辑 2: 我更改了 @model IEnumerable<ViewModel>@model List<ViewModel>并且错误 Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable 已更正。

编辑 3: 我能够得到 Textbox 的值和 CheckBox进入 Controller 但是RadioButtonDropDownList's selected values cant be identified at the [HttpPost]` 函数?我在这里缺少什么?

@for (i = 0; i < Model.Count(); ++i)
{
 if (Model[i].TypeId == 4)
                    {
                        //radiobutton
                        for (int j = 0; j < Model[i].Options.Count(); ++j)
                        {
                    <div>
                        @Html.HiddenFor(m => m[i].Options[j].OptionId)                        
                        @Html.HiddenFor(m => m[i].Options[j].OptionValue)
                        @Html.HiddenFor(m => m[i].Options[j].Id)

                        @Html.RadioButtonFor(m => m[i].Options[j].Value, @Model[i].Options[j].DisplayText)
                        @Html.DisplayFor(m => m[i].Options[j].DisplayText)
                    </div>

                        }
                    }
}

最佳答案

我建议:

  1. 使用强类型 View
  2. 使用for(i = 0; ...; ...) 循环,否则不能这么简单

另一种方法可能是(请不要使用这种方法):

  1. 在 JS post 事件上创建列表的 JSON 数组
  2. 使用此数据向 Controller 发送 AJAX POST 请求

关于c# - 从 View 获取 List<ViewModel> 到 Controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18695073/

相关文章:

c# - 在 XmlSerializer 的输出中交换 xsd 和 xsi

c# - 以编程方式注册 C#/VB.NET COM dll

asp.net-mvc-4 - 如何输出Request.CreateResponse方法的json对象

c# - Paypal Ipn 与 asp.net MVC 集成

c# - 在 MVC 4 中为 3 层架构配置 Ninject

c# - Asp.net Paypal 返回 Url 要求

c# - 运算符 '<' 不能应用于类型 'long' 和 'ulong' 的操作数

sql-server - 如何检查 ASP.NET MVC4 应用程序性能?

c# - ASP.NET MVC 5 Identity with Model First

javascript - 脚本应该去哪里 MVC4/Razor?