gpt4 book ai didi

asp.net - MVC 模型未更新

转载 作者:行者123 更新时间:2023-12-04 00:15:29 25 4
gpt4 key购买 nike

型号 :

class Address
{
public string City { get; set; }
public string Zip { get; set; }
}

Controller :

[HttpPost]
public ActionResult GetAddress(Address model)
{
if (!String.IsNullOrEmpty(model.Zip))
{
model.City = GetCityByZip(model.Zip);
}
return View(model);
}

观点 :

<div class="formrow">
@Html.LabelFor(model => model.City)
@Html.TextBoxFor(model => model.City)
@Html.ValidationMessageFor(model => model.City)
</div>
<div class="formrow">
@Html.LabelFor(model => model.Zip)
@Html.TextBoxFor(model => model.Zip)
@Html.ValidationMessageFor(model => model.Zip)
</div>

问题是每当城市被修改时,它永远不会反射(reflect)在 View 上。在调试期间, model.City包含正确的值,但未显示在 View 中。甚至像 @Html.TextBoxFor(model => model.City) 这样简单的东西不显示正确的 model.City值(value)。

最佳答案

当您更新和返回模型时,HtmlHelpers 从模型状态而不是模型中获取模型值。为了更新和返回模型,在你的 post 方法中添加这行代码:

ModelState.Clear();

或者您可以在 ModelState 本身中设置 city 的值:
ModelState["City"].Value = GetCityByZip(model.Zip);

关于asp.net - MVC 模型未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11838335/

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