我有一个ASP.NET MVC4应用程序,其中有一个页面(索引),其中用户可以从DropDownList中选择一个项目。提交后,控制器将根据列表中选定的项目,将不同的PartialView名称返回到另一个视图(创建)。每个部分都有自己的ViewModel,当PartialView从Controller发送到时创建 - 查看它被正确渲染。为了达到这个目的,我制作了一个普通的ViewModel和其他几个从这个普通ViewModel派生出来的视图模型。 创建 - 视图具有一般视图模型作为模型,并且将在创建 - 视图中呈现的部分具有匹配的派生类型作为模型。返回不同类型的ViewModel回到控制器
但是,这里的问题是,当我在PartialView上提交表单时,我必须在Controller中取回正确的ViewModel。接受一般ViewModel作为参数将无法正常工作,因为我无法将其向下转换到正确的ViewModel。下面是我的一些示例代码:
的ViewModels:
public class PropertyViewModel
{
public string ViewName { get; set; }
public String Name { get; set; }
public String Description { get; set; }
}
public class IntegerViewModel : PropertyViewModel
{
public int MinValue { get; set; }
public int MaxValue { get; set; }
}
public class TextViewModel : PropertyViewModel
{
public int MaxLength { get; set; }
}
控制器:
public ActionResult Create(String partialName)
{
var model = GetViewModelFromName(partialName);
return View(model);
}
[HttpPost]
public ActionResult Create(???)
{
//What to do here and what kind of parameter should I expect?
}
是否有一个 '干净' 的方式做到这一点?有谁知道如何做到这一点?
更新:
我,似乎工作的解决方案。在PartialView我设置了actionName和形式的controllerName,就像这样:
@using (Html.BeginForm("CreateIntegerProperty", "Property")) {
//Formstuff...
}
@using (Html.BeginForm("CreateTextProperty", "Property")) {
//Formstuff...
}
在我控制我的所有不同的操作(每个对应一个PartialViews的)。这似乎工作。现在是干净的方式来做到这一点?如果有人想出一个更好的主意,请让我知道!
非常好的主意。我将您的答案设置为我的问题的答案,因为现在一切正常,并且您的解决方案得到了增强! :) – Abbas 2012-03-15 10:18:21
谢谢。很高兴得到了帮助。 :-) – 2012-03-15 10:20:49