Html.TextBoxFor不使用新Model对象的值
本文关键字:Model 对象 TextBoxFor Html | 更新日期: 2023-09-27 17:59:31
我正在开发我的第一个MVC Web应用程序(使用Razor和C#),我遇到了一个奇怪的行为。
我正在编辑一行数据,并使用ajax调用来提交和重新显示数据。只要更改现有数据并存储它,一切都很好。同样,如果我只是重新显示提交的"行",没有问题。
然而,我想显示一个"新"行,其中保留了旧行中的一些值,而去掉了其余的值。
然而,当我将新行对象提交到Partial View时,@Html…不会拾取"blanked"out值。。。。助手。但是,如果我直接显示模型的属性,它具有正确的(空白)值。
以下是我的代码的相关部分:控制器方法:[HttpPost]公共ActionResult EditLineForm(SkuRequestLine-ln){SkuRequestLine换行符=null;
try
{
if (ln.Store(true))
{
ViewData["prodcatdesc"] = DataConnection.GetProductCategory(ln.Category).description;
newline = new SkuRequestLine();
newline.Copy(ln);
newline.Line = DataConnection.NextSkuRequestLineNumber(ln.Request);
newline.Comments = "";
newline.Description = "";
newline.Vendorsku = "";
return PartialView("EditLineForm", newline); // this line is being executed.
}
else
{
return PartialView("EditLineForm", ln);
}
}
catch (Exception ex)
{
List<string> msgs = new List<string>();
while (ex != null)
{
msgs.Add(ex.Message);
ex = ex.InnerException;
}
return PartialView("EditLineForm", ln);
}
}
Razor代码:
@model Sku_Management.Models.SkuRequestLine
@using (Ajax.BeginForm("EditLineForm", "SkuRequest", new AjaxOptions { OnSuccess = "UpdateLineList" }))
{
.
.
.
<tr>
<td>
<span class="editor-label">
@Html.LabelFor(model => model.Description)
</span>
</td>
<td colspan="5">
<span class="editor-field">
@Html.TextBoxFor(model => model.Description, new { @class = "fortywide" }) // Displays the Description from the edited Line passed in. Not what what Model.Description is.
@Html.ValidationMessageFor(model => model.Description)
</span>
<span>|@Model.Description|</span> // Displays "||" which is what it should be since Model.Description is blank.
</td>
</tr>
我唯一能想到的就是模型=>模型。描述使用的是模型的缓存版本,而不是传递到PartialView调用中的新模型。
我花了一整天的时间在网上搜索类似的东西,但我找不到任何可以描述这种行为的东西。
有没有其他人遇到过这种情况,知道我错在哪里?
感谢
这是因为HTMLHelpers在使用Model之前会在ModelState中查找值。
您必须清除ModelState条目才能使其工作。