c# - 在控制器和多个视图之间传递模型
问题描述
我是 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。
解决方案
如果你想保持 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>
}
推荐阅读
- csv - Google表格中importdata函数的单元格限制是多少?
- pip - 在 Kaggle 内核中隐藏来自 pip 的“要求已经满足”警告
- javascript - Vaadin 键盘滚动
- java - android:将我的库从 android 升级到 androidx,但没有找到此类 SlideCallback
- bootstrap-4 - 是否有可能在所有小屏幕设备中使 bootstrap 4 中的额外小类响应
- opengl-4 - OpenGL - MSAA 不支持浮点纹理吗?
- neo4j - 在 Neo4j Graph Data Science 中,我可以使用自定义类型名称通过密码创建图形吗?
- python-3.x - Groupby 并在 Pandas 中打印整个数据框
- next.js - PWA 独立窗口是否有可能具有“保持领先”功能?
- c# - SQL 字符串或普通字符串