这是我的情况——
我有两个嵌套的 View 模型:
<%=Html.EditorFor(x => x.DisplayEntitiesWithRadioboxesViewModel)%><br />
位于它们的父级(StructureViewModel)中,我可以轻松填充嵌套的 ViewModel 并将其传递给主 View :
在 Controller 内 - 示例
var moveDepartment = new StructureViewModel();
moveDepartment.DisplayEntitiesWithRadioboxesViewModel = fullDepartmentList.Select(x => new DisplayEntityViewModel
{
Id = x.Id,
Path = x.Path,
PathLevel = x.PathLevel,
Description = x.Description,
});
return View(moveDepartment);
EditorTemplete - 示例
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Site.Areas.Administration.ViewModel.DisplayEntityViewModel>>" %>
<table class="aligncenter"><%
if (Model != null)
{
foreach (var entity in Model)
{%>
<tr class="tRow">
<td style="text-align:left; text-indent:<%=Html.Encode(entity.PathLevel)%>em">
<%=Html.Encode(entity.Description)%>
<%=Html.RadioButton("radiobutton",entity.Id)%>
</td>
</tr><%
}
}%>
</table>
namespace Site.Areas.Administration.ViewModel
{
public class DisplayEntityViewModel
{
public int Id { get; set; }
public string Path { get; set; }
public string PathLevel { get; set; }
public string Description { get; set; }
}
}
但是,当我尝试撤回此信息时,嵌套的 ViewModel 为空:
[HttpPost]
public ActionResult Move(StructureViewModel StructureViewModel)
当我将鼠标悬停在
StructureViewModel
上时它只包含父 ViewModel 上的数据集。例如:可以看到隐藏值但 DisplayEntitiesWithRadioboxesViewModel = null。我知道如何访问
DisplayEntitiesWithRadioboxesViewModel
的唯一方法是使用 FormCollection
并遍历 FormCollection
并从嵌套的 ViewModel 中提取我需要的信息。然而,这似乎不正确,正如我在那里发现的那样,然后我必须重新填充
DisplayEntitiesWithRadioboxesViewModel
来自 FormCollection
的值,例如,如果发生错误并且需要将用户发送回同一个 View 。我曾尝试搜索网络/书籍,但找不到解决方案。
有没有更好的办法?
在此先感谢您的帮助。
And why did you use an EditorFor for a simple dropdown, which is easily to use with DropDownFor
现在已更改为使用 DropDownFor。
what is the Key of the DisplayEntitiesWithRadioboxesViewModel value in FormCollection
{string[3]}
[0] = "DisplayEntitiesWithRadioboxesViewModel.radiobutton"
[1] = "Action"
[2] = "OldParentId"
克莱尔:-)
最佳答案
一旦您了解了它的工作原理,您的问题就很常见,并且很容易解决。
现在你有一个 View 模型,它的属性是 IEnumerable<T>
(与泛型参数是什么无关)。您正在尝试将项目传递给 View 并填充 IEnumerable<T>
当响应返回时使用相同的值,使用最初写入页面的值,并使用所选项目进行扩充(至少从您发布的代码来看,这将有助于您在问题中说明您的确切意图) .您在这里遇到的问题是您必须以一种可以返回它们的方式将这些值发送到页面。
现在让我说你可能应该不是 正在使用这种技术。如果您需要服务器端,通常只返回选择并再次生成列表是一个更好的主意。
从外观上看,您要返回整个列表,然后查找选定的项目,这毕竟是下拉或单选按钮组的点。为了恢复选择, Controller 操作的参数必须具有与传回的变量相匹配的属性。在这种情况下,您似乎正在使用参数名称 radiobutton
对于所有单选按钮(下拉列表也是如此,只有它使用列表的名称)。无论选择哪一个,与它关联的值都会以该名称返回。 MVC 框架负责尝试找到指定了尽可能多名称的适当操作。
您需要为操作参数使用的是一个新类,该类包含所有提交回服务器的字段名称的属性!或者当然你可以简单地添加 radiobutton
您的属性(property)StructureViewModel
也。事实上,您会注意到它已经在尝试设置该值,只是它当前不存在于您的 View 模型中。但是,您仍然不会收到原始列表,但这没关系,因为即使您确实收到了原始列表,上面也没有标识符来让您知道选择了哪个项目!
希望这可以帮助您了解正在发生的事情,如果您有更多问题,请提问。
关于asp.net - 如何使用嵌套 View 模型获取 EditorFor 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3582089/