c# - 将不同类型的ViewModel返回给 Controller

标签 c# asp.net-mvc mvvm partial-views asp.net-mvc-4

我有一个ASP.NET MVC4应用程序,在该应用程序中的某个点上有一个页面(索引),用户可以在其中选择DropDownList。提交此内容后, Controller 将根据列表中的选定项将另一个PartialView-name返回给另一个View(创建)。每个局部都有自己的ViewModel,并且当PartialView从Controller发送到Create-View时,它会正确呈现。为此,我制作了一个通用的ViewModel和从该通用的ViewModel派生的其他几个 View 模型。 Create-view的常规ViewModel为Model,Partials将在Create-view中呈现,其匹配的派生类型为Model。

但是这里的问题是,当我在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; }
}

Controller :
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...
}

在我的 Controller 中,我具有所有不同的操作(每个PartialViews都有一个)。这似乎有效。现在这是一种干净的方法吗?如果有人提出更好的主意,请告诉我!

最佳答案

如果您的解决方案可行,那就继续吧。对我来说似乎很好。如果您不愿意为每个操作使用相同的URL,就会出现唯一的问题。

如果愿意,可以通过在基本ViewModel中添加Action和Controller名称来对其进行一点点增强,如下所示:

public class PropertyViewModel
{
    public string ViewName { get; set; }
    public String Name { get; set; }
    public String Description { get; set; }
    public String Controller { get; set; }
    public String Action { get; set; }
}

然后这样做:
@using (Html.BeginForm(Model.Action, Model.Controller)) {
    //Formstuff...
}

如果这意味着您现在可以为表单使用相同的View(或部分 View ,或其他任何内容),这将是值得的。

如果您确实希望每个 Action 都使用相同的URL,那么一种方法是覆盖OnModelBinding,但是我个人可能不会打扰。

关于c# - 将不同类型的ViewModel返回给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9716784/

相关文章:

c# - MenuItem.IsEnabled 绑定(bind)到公共(public) bool 值

java - Android 数据绑定(bind) layout_width 和 layout_height

c# - Xamarin Forms Exrin Framework将容器推为模态?

c# - 从 DataGrid 中自动删除新行

c# - C# 中有没有办法让 Type 包含自身?

c# - 在 C# Windows 应用程序中指定主题 id 的位置

c# - 您如何查看已注册的 httphandlers 的集合?

asp.net-mvc - 您可以从其项目文件夹运行 ASP.NET MVC 应用程序吗?

c# - 如何使用包含资源值的IController Execute()返回View?

c# - Cookie 在浏览器 session 结束时过期