【问题标题】:Model attributes not passed to next view模型属性未传递到下一个视图
【发布时间】:2020-09-16 10:05:01
【问题描述】:

我正在尝试在 asp.net mvc 的不同视图中重用模型。但是如果模型被传递到下一个视图并提交了新属性,那么旧的值就会丢失。

这里是我正在使用的代码示例:

型号

    public class ExampleModel
    {
        public string Attribut1 { get; set; }
        public string Attribut2 { get; set; }
    }

控制器

    public class HomeController : Controller
    {
        public IActionResult Page1()
        {
            return View(new ExampleModel());
        }

        public IActionResult Page1Check(ExampleModel model)
        {
            return View("Page2", model);
        }

        public IActionResult Page2Check(ExampleModel model)
        {
            return View("Page2", model);
        }
    }

查看1

@model Example.Models.ExampleModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

    <form asp-controller="Home" asp-action="Page1Check">
        <label asp-for="Attribut1"></label>
        <input asp-for="Attribut1" placeholder="Attribut1" />
        <button type="submit">Submit</button>
    </form>

视图2

@model Example.Models.ExampleModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

    <form asp-controller="Home" asp-action="Page2Check">
        <label asp-for="Attribut2"></label>
        <input asp-for="Attribut2" placeholder="Attribut2" />
        <button type="submit">Submit</button>
    </form>

如果我打开 Page1,则会创建一个新模型。如果在Page1中输入了attribut1并提交了Page1Check,则调用并填充了attribut1。现在模型被传递到 page2。在这里,attribut2 被填写并提交。但是,如果我检查 Page2Check 内部的模型,attribut1 为空,并且只有 attribut2 被填充。

奇怪的是,如果我在 page2 视图中检查 attribut1,它仍然存在。只有在提交之后,attribut1 才会消失。

我错过了什么,如何防止提交后填充的属性为空?

【问题讨论】:

    标签: c# asp.net model-view-controller


    【解决方案1】:

    为了在提交相应表单时将一条数据从用户浏览器发送到服务器,它必须包含在将发送到服务器的 HTML 元素中(例如,&lt;input&gt;&lt;select&gt;)。

    在您的第一个视图中,您有一个Attribut1 的输入,但没有Attribut2 的输入,因此Attribut2 不会成为提交视图1 中的表单时发送到服务器的数据的一部分。视图 2 中的 Attribut1 也是如此。

    要解决这个问题,您可以为每个视图添加隐藏字段,由 &lt;form&gt; 标签包含,以存储数据:

    • 对于视图 1,添加 &lt;input type="hidden" asp-for="Attribut2" /&gt;
    • 对于视图 2,添加 &lt;input type="hidden" asp-for="Attribut1" /&gt;

    例如,视图 1 的表单现在如下所示:

    <form asp-controller="Home" asp-action="Page1Check">
        <label asp-for="Attribut1"></label>
        <input asp-for="Attribut1" placeholder="Attribut1" />
        <input type="hidden" asp-for="Attribut2" />
        <button type="submit">Submit</button>
    </form>
    

    【讨论】:

      猜你喜欢
      • 2011-10-22
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 2018-01-18
      • 2014-04-03
      • 2021-12-01
      • 2012-07-12
      相关资源
      最近更新 更多