gpt4 book ai didi

c# - MVC4 - 表单不显示新模型值

转载 作者:行者123 更新时间:2023-11-30 22:11:42 25 4
gpt4 key购买 nike

我有一个包含 2 个 Action 的 Controller :1 个用于显示表单,2 个用于处理提交的表单。像这样:

public ActionResult Create()
{
TestModel model = new TestModel() { Value1 = "aaa" };
return View(model);
}

[HttpPost]
public ActionResult Create(TestModel model)
{
model.Value2 = "bbb";
return View(model);
}

如您所见,我用“aaa”预填充了 Value1,因此它出现在表单上 - 这部分工作正常。但是,当我提交表单时,我想填充模型对象的其他属性并使用相同的 View 重新显示表单。

问题是在提交表单时仍然显示原始模型对象而不是更新后的模型对象,即只有 Value1 填充了“aaa”而 Value2 为空。

我使用的 View 是通过脚手架选项自动生成的 View :

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
<legend>TestModel</legend>

<div class="editor-label">
@Html.LabelFor(model => model.Value1)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Value1)
@Html.ValidationMessageFor(model => model.Value1)
</div>

<div class="editor-label">
@Html.LabelFor(model => model.Value2)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Value2)
@Html.ValidationMessageFor(model => model.Value2)
</div>

<p>
<input type="submit" value="Save" />
</p>
</fieldset>

最佳答案

您必须调用 ModelState.Clear() 以便结果符合预期。当 POSTed 数据被发送回客户端时,MVC 会做出假设。但请注意,手动清除它可能会导致不良结果......

您可以在此处阅读更多信息:Asp.net MVC ModelState.Clearhttp://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

关于c# - MVC4 - 表单不显示新模型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20119507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com