我有一个 View
允许编辑 List
的 ViewModel
.代码一直工作到显示功能。但是我无法从 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 但是RadioButton
和 DropDownList'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>
}
}
}
最佳答案
我建议:
- 使用强类型 View
- 使用
for(i = 0; ...; ...)
循环,否则不能这么简单
另一种方法可能是(请不要使用这种方法):
- 在 JS post 事件上创建列表的 JSON 数组
- 使用此数据向 Controller 发送 AJAX POST 请求
关于c# - 从 View 获取 List<ViewModel> 到 Controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18695073/