在控制器和多个视图之间传递模型

Passing model between controller and multiple views

我是 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");
    }

视图 1 看起来像这样:

<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.

如果你想保持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>


}

结果: