首页 > 解决方案 > 在控制器和多个视图之间传递模型

问题描述

我是 asp.net 的新手,遇到了一个非常基本的问题(在 c# 方面也没有太多经验,所以我可能在滥用术语)。我有 2 个视图连接到同一模型。在第一个视图中,用户输入为模型属性之一分配了一个值——我们称之为 A1。在依赖于 A1 值的第二个视图中,用户输入填充了模型属性的其余部分,如下例所示。

控制器看起来像这样:

    public ActionResult ClalledFromView1(MyModel model)
    {
        return View("View2", model);
    }

    public ActionResult CalledFromView2(MyModel model)
    {
        model.CheckAllAttributes();
        return View("View3");
    }

View1 看起来像这样:

<html>
    @using (Html.BeginForm("CalledFromView1", "ControllerName", FormMethod.Post))
    {
        @Html.TextBoxFor(model => model.A1)
        <button type="submit">Submit</button>
    }
</html>

视图 2 看起来像这样:

<html>
    @using (Html.BeginForm("CalledFromView2", "ControllerName", FormMethod.Post))
    {
        @if (Model.A1 == "some value")
        {
            @Html.TextBoxFor(model => model.A2)
        }
        else
        {
            @Html.TextBoxFor(model => model.A3)
        }
        <button type="submit">Submit</button>
    }
</html>

发生的情况是,调用 CalledFromView2 时,A1 为空,但 A2 已填充,并且与 A1 的原始值一致。我希望在控制器和两个视图之间来回传递相同的模型而不清除任何属性。TIA。

标签: c#asp.net-mvcasp.net-corerazor

解决方案


如果你想保持 A1 值通过,你可以像这样添加一个隐藏的输入。

视图2:

 @using (Html.BeginForm("CalledFromView2", "ControllerName", FormMethod.Post))
    {
        @Html.TextBoxFor(model => model.A1, new { @hidden = "hidden" })
        @if (Model.A1 == "some value")
        {
            @Html.TextBoxFor(model => model.A2)
        }
        else
        {
            @Html.TextBoxFor(model => model.A3)
        }
        <button type="submit">Submit</button>
    }

这是一个演示:

模型:

public class ModelA
    {
        public string A1 { get; set; }
        public string A2 { get; set; }
        public string A3 { get; set; }


    }

控制器(测试3):

public IActionResult TestModelA()
        {
            return View();
        }
        public ActionResult CalledFromView1(ModelA model)
        {
            return View("View2", model);
        }

        public ActionResult CalledFromView2(ModelA model)
        {
            //model.CheckAllAttributes();
            return View("View3");
        }

测试模型A:

@using (Html.BeginForm("CalledFromView1", "Test3", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.A1)
    <button type="submit">Submit</button>
}

视图2:

@using (Html.BeginForm("CalledFromView2", "Test3", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.A1, new { @hidden = "hidden" })
    @if (Model.A1 == "some value")
    {
        @Html.TextBoxFor(model => model.A2)
    }
    else
    {
        @Html.TextBoxFor(model => model.A3)
    }
    <button type="submit">Submit</button>


}

结果: 在此处输入图像描述


推荐阅读