我有一个通过ajax提交给Controller的表单。 Controller从Model收集数据,然后创建一个新的ViewModel并将其传递给部分视图,然后在Client上更新。
问题是文本框没有按预期清除。消息按预期到达视图,因此没有清除文本框没有意义。
然而,这似乎是一个浏览器问题,因为这是生成的HTML,注意,该值没有任何内容:
<input id="Address_Address1" name="Address.Address1" type="text" value="" />
然而,用户会看到之前输入的值。
这是控制器:
//Process Order Here
//This should clear out the ViewModel.
order = new OrderViewModel();
order.Message = "Report Added to your cart";
return PartialView("_NewOrderPartial", order);
这是部分视图:
@model NTC.PropertySearch.Models.OrderViewModel
@using (Ajax.BeginForm("NewOrder", "Order", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "neworder" }))
{
<div id="neworder">
<table>
<tr>
<th style="width: 300px;">
<h3>Enter property address below</h3>
</th>
<th style="width: 30px;"></th>
<th style="width: 300px;">
<h3>Choose your report below</h3>
</th>
</tr>
<tr>
<td>
<div class="form">
<table>
<tr>
<td>
@Html.LabelFor(m => m.Address.Address1)
</td>
<td>
@Html.TextBoxFor(m => m.Address.Address1)
</td>
<td>
@Html.ValidationMessageFor(m => m.Address.Address1)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(m => m.Address.Address2)
</td>
<td>
@Html.TextBoxFor(m => m.Address.Address2)
</td>
<td>
@Html.ValidationMessageFor(m => m.Address.Address2)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(m => m.Address.City)
</td>
<td>
@Html.TextBoxFor(m => m.Address.City)
</td>
<td>
@Html.ValidationMessageFor(m => m.Address.City)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(m => m.Address.State)
</td>
<td>
@Html.TextBoxFor(m => m.Address.State)
</td>
<td>
@Html.ValidationMessageFor(m => m.Address.State)
</td>
</tr>
<tr>
<td>
@Html.LabelFor(m => m.Address.ZipCode)
</td>
<td>
@Html.TextBoxFor(m => m.Address.ZipCode)
</td>
<td>
@Html.ValidationMessageFor(m => m.Address.ZipCode)
</td>
</tr>
</table>
<input type="submit" value="Add Report" />
@Html.DisplayFor(m=> m.Message)
</div>
</td>
</tr>
</table>
</div>
答案 0 :(得分:11)
原因是因为TextBox等Html帮助程序在绑定它们的值时首先查看ModelState,然后才在View模型中查看。当人们尝试在HttpPost控制器操作中修改/清除视图模型的某些值时,通常会发生这种情况。相应的视图将使用初始POSTed值而不是视图模型中的值。
您应该在控制器操作中清除ModelState:
ModelState.Clear();
order = new OrderViewModel();
或者,如果您不想清除整个ModelState(尽管在您重新初始化整个视图模型时似乎就是这种情况),您只能清除一些您想要修改的属性:
ModelState.Remove("SomeProperty");
viewModel.SomeProperty = "some new value";