gpt4 book ai didi

asp.net-mvc - MVC 4 文本框未在回发时更新

转载 作者:行者123 更新时间:2023-12-02 08:31:40 26 4
gpt4 key购买 nike

我有一个使用模型 View 对象的表单,该对象不会在提交表单的回发时更新文本框值。在提交表单时,我编辑绑定(bind)到文本框的对象的属性。当表单返回时,对象属性仍然改变,但文本框值没有改变。这就像文本框值被缓存并且不会改变。我该如何解决这个问题?

文本框默认值:""

文本框代码:

@Html.TextBoxFor(m => m.Project.tNumber, new { @readonly = "readonly", @class = "readonly" })

对象属性:

[Display(Name = "T Number")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string tNumber { get; set; }

Controller 操作方法:

[Authorize(Roles = "Admin, OrderEntryManager")]
[HttpPost]
public ActionResult Verify(string submit, OrderEntryEdit model)
{
MembershipUser user = Membership.GetUser(User.Identity.Name);
int userId = WebSecurity.GetUserId(User.Identity.Name);
if (userId > 0)
{
if (ModelState.IsValid)
{
string ButtCommand = submit;
switch (ButtCommand)
{
case "Create Order":
if (model.CreateOrder(userId))
{
ViewBag.Status = "success";
ViewBag.Message = "The order has been created.";
}
else
{
ViewBag.Status = "error";
ViewBag.Message = "There was a problem in trying to create this order.";
}
default:
ViewBag.Status = "error";
ViewBag.Message = "Unrecognized form action.";
}
}
}
else
{
ViewBag.Status = "error";
ViewBag.Message = "Unrecognized user.";
}
return View("Verify", model);
}

View 模型方法:

public class OrderEntryEdit : OrderEntry
{
public OrderEntryEdit()
{
base.Project = new Project();
base.ShipTo = new ShipTo();
base.SoldTo = new SoldTo();
base.Unit = new List<Unit>();
}
//method simplified, but is reaching this method
public Boolean CreateOrder(int adminUserId = 0)
{
this.Project.tNumber = "T123456";
return true;
}
}

文本框值:""

编辑:用这个替换文本框的代码:

<input type="text" readonly="readonly" class="readonly" value="@Model.Project.tNumber" />

已解决问题。显然,文本框正在被缓存。简而言之,不要使用 Razor 语法,好的旧 html 可以正常工作。我希望这对其他人有帮助!

最佳答案

TextBoxFor、DropDownListFor 等编辑器使用 ModelState 值而不是您传递给 View 的模型中的值。 ModelState 包含用户通过表单提交的值。

您可以通过在操作中调用 ModelState.Clear() 来清除整个 ModelState。然后,编辑器将改用您模型中的值。

这有点违反直觉。 this thread上的解释终于对我有意义了。

The reason we use the posted value for editors rather than the model value is that the model may not be able to contain the value that the user typed. Imagine in your "int" editor the user had typed "dog". You want to display an error message which says "dog is not valid", and leave "dog" in the editor field. However, your model is an int: there's no way it can store "dog". So we keep the old value.

关于asp.net-mvc - MVC 4 文本框未在回发时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26062359/

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