【问题标题】:How to get model from Partial View in MVC如何从 MVC 中的局部视图中获取模型
【发布时间】:2015-02-08 23:00:41
【问题描述】:

我有一个主索引视图,我从中调用名为 Create 的视图,我将要创建的小部件的类型作为字符串传递到该视图中。

索引视图:

<a href="@Url.Action("Create", "WidgetEditor", new { wType = "image" })"><i class="fa fa-image"></i> Create Image Widget</a> - 
<a href="@Url.Action("Create", "WidgetEditor", new { wType = "text"  })"><i class="fa fa-file-text"></i> Create Text Widget</a>

创建动作:

public ActionResult Create(string wType)
{
    ViewBag.wType = wType;
    return View();
}

然后通过 ViewBag.wType 将类型传递到视图中,并在 Create View 中对其进行评估

创建视图:

@using (Html.BeginForm())
{
    <section class="row">
    @{
        if (ViewBag.wType == "image")
        {
            Html.RenderPartial("~/Views/WidgetEditor/_CreateImageWidget.cshtml");
        }
        else if (ViewBag.wType == "text")
        {
            Html.RenderPartial("~/Views/WidgetEditor/_CreateTextWidget.cshtml");
        }
    }
    </section>
}   

并根据此加载适当的局部视图。 部分视图有不同的模型,所以当提交表单时,我不知道哪个模型是如何传回的。来自 _CreateImageWidget 或 _CreateTextWidget 的那个。

如果 HttpPost 控制器看起来像这样

[HttpPost]
public ActionResult Create(DisplayWidgetImageViewModel imageModel, DisplayWidgetTextViewModel textModel)
{
    return new ViewResult();
}

如果选择了 _CreateImageWidget 部分,我将获得填充的 imageModel,如果选择了 _CreateTextWidget 部分,我将获得填充的 textMode。

如果小部件类型的数量不变,这是可以接受的,但事实并非如此。 有没有办法从局部视图中获取某种特定模型并知道/找出它是哪一个或者我这样做完全错误的方式?

【问题讨论】:

标签: ajax model-view-controller controller


【解决方案1】:

您可以在单个页面中创建多个表单。您还可以对每个部分使用不同的操作方法:

@using (Html.BeginForm("Action", "Controller")) {
    Html.RenderPartial("~/Views/WidgetEditor/_CreateImageWidget.cshtml")
}

这一切都无需使用 Ajax。

【讨论】:

  • 这是一个进步,但如果有 20 个小部件,我最终会得到 20 个表单......虽然如果表单是部分视图的一部分......但我仍然会有很多动作...
  • 不幸的是,默认绑定器必须知道显式类型。您可以做的另一件事是设置自定义活页夹。自定义绑定器可以作用于父类型或类。这样你只使用一个动作。
【解决方案2】:

我用这个答案解决了我的问题:determine-the-model-of-a-partial-view-from-the-controller-within-mvc

还有其他几个链接提供更多资源。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    相关资源
    最近更新 更多