C# 从具有PartialView的表单中收集数据的适当方法是什么?该视图会根据条件进行更改
我有一个C# 从具有PartialView的表单中收集数据的适当方法是什么?该视图会根据条件进行更改,c#,asp.net-mvc,entity-framework,asp.net-mvc-5,entity-framework-6,C#,Asp.net Mvc,Entity Framework,Asp.net Mvc 5,Entity Framework 6,我有一个ParentView,它自己几乎没有字段。此ParentView根据在ParentView中选择的下拉列表,从3个不同的PartialView中呈现一个PartialView。因此有PartialViewA,PartialViewB和PartialViewC。一次只渲染一个。每个都有自己的表,即模型类 例如:partialViewModel:ParentViewModel。。等等 我认为收集数据的方法之一是使用FormCollection。 因此,如果dropdownvalue是一个值,
ParentView
,它自己几乎没有字段。此ParentView
根据在ParentView中选择的下拉列表,从3个不同的PartialView中呈现一个PartialView
。因此有PartialViewA
,PartialViewB
和PartialViewC
。一次只渲染一个。每个都有自己的表,即模型类
例如:partialViewModel:ParentViewModel
。。等等
我认为收集数据的方法之一是使用FormCollection
。
因此,如果dropdownvalue
是一个值,我就知道我必须选择哪些键以及存储在哪里
但是有没有更优雅的方式来绑定数据呢?如果只有一个视图和模型,我可以在绑定中简单地使用Modelclass。例如:公共的
[HttpPost]
ActionResult Create(CustomerClass cust)
如果指定具有子局部视图模型的父视图模型,如下所示:
public class ParentViewModel
{
public ParentViewModel()
{
PartialViewModel1 = new PartialViewModel1();
PartialViewModel2 = new PartialViewModel2();
PartialViewModel3 = new PartialViewModel3();
}
public string PartialViewType { get; set; } /* Value to determine which view to show */
public PartialViewModel1 PartialViewModel1 { get; set; }
public PartialViewModel2 PartialViewModel2 { get; set; }
public PartialViewModel3 PartialViewModel3 { get; set; }
}
public class PartialViewModel1
{
public string Property1_1 { get; set; }
public string Property1_2 { get; set; }
public string Property1_3 { get; set; }
}
其中,局部视图模型(例如PartialViewModel1
)具有该视图模型特有的属性,如下所示:
public class ParentViewModel
{
public ParentViewModel()
{
PartialViewModel1 = new PartialViewModel1();
PartialViewModel2 = new PartialViewModel2();
PartialViewModel3 = new PartialViewModel3();
}
public string PartialViewType { get; set; } /* Value to determine which view to show */
public PartialViewModel1 PartialViewModel1 { get; set; }
public PartialViewModel2 PartialViewModel2 { get; set; }
public PartialViewModel3 PartialViewModel3 { get; set; }
}
public class PartialViewModel1
{
public string Property1_1 { get; set; }
public string Property1_2 { get; set; }
public string Property1_3 { get; set; }
}
您可以指定父视图,使其具有一个包含部分视图的表单,该表单可以在客户端通过一点JavaScript进行切换(我没有包括,但应该足够简单:):
因此,现在您可以通过ParentViewModel
提交控制器上的更新
操作:
[HttpPost]
public ActionResult Update(ParentViewModel model)
{
// Do whatever processing required.
// You can switch on model.PartialViewType to process the appropriate PartialView fields
return View("Index", model);
}
提交时,模型应包含已在相应局部视图模型属性中提交的内容
希望这有帮助 您可以使用ajax post并在不同的操作之间切换,否则我会在父视图模型中为每个子视图模型添加一个引用(这还不错)。@giovaniromio有一个提交按钮,用于提交整个表单(父视图和部分视图)。我在formcollection对象中拥有所有键(属于父级的键和属于渲染部分视图的键)。但是我想知道我是否可以在这个对象上使用
UpdateModel
等来填充ParentModel和Partialview model的实例,这将非常好。根据数据集的大小,这可能不是非常有效。不过,这可能是一个很好的“稍后尝试并重构”的例子,因为它肯定会起作用+1适用于坚持MVC基础的工作解决方案。似乎没有在post上填充PartialViewModel。所有属性都为空。我将html输入字段与name=“Property1_1”
一起使用,检查PartialView视图顶部的@model
声明是否设置为@model.ParentViewModel
(如答案所示)。这将导致发出以下HTML
,然后在post上正确绑定到模型。