首页 文章

Html Helper 可能缓存输入值

提问于
浏览
2

我正在使用视图模型和部分视图来使用 AJAX 插入行。插入新行时,ViewModel 的 ID(AttributeDefinitionID)设置为零。保存时,ID 会更新并发送回视图。然而,绑定到 ID 的帮助程序似乎仍然具有旧值。

查看模型

public class AttributeEntryViewModel
{
    public int AttributeDefinitionID { get; set; }

    [Required]
    [MaxLength(255, ErrorMessage = "Name must be less than 
                                    255 characters in length.")]
    public string Name { get; set; }
}

局部视图“_AttributeEntryPartial.cshtml”

@model ICMDB.ViewModels.AttributeEntryViewModel

<tr id ="@Model.AttributeDefinitionID" >
   @Html.HiddenFor(model => model.AttributeDefinitionID)

   <td>
      @Html.EditorFor(model => model.Name)
      @Html.ValidationMessageFor(model => model.Name)
   </td>
   <td>
      <a href="#" onclick="RemoveAttribute(@Model.AttributeDefinitionID); 
                           return false;">Remove</a>
   </td>
</tr>

由于某种原因,Html Helper Html.HiddenFor没有绑定到正确的值并产生以下 Html:

<tr id="40850">
    <input id="AttributeDefinitionID" type="hidden" value="0" 
           name="AttributeDefinitionID" data-val-required="The 
           AttributeDefinitionID field is required." data-val-number= "The 
           field AttributeDefinitionID must be a number." data-val="true">

您可以看到它已在行标记(<tr id = "40850">)中正确插入了 ID,但未在输入标记(value="0")中插入。这应该是value="40850"

有任何想法吗? Html Helper 或浏览器是否缓存了值?

编辑: AJAX 函数 AddAttribute 只调用同名的控制器函数,并将得到的部分(上面列出的部分)附加到表中:

function AddAttribute() {
   // and send it as AJAX request
   $.ajax({
      url: '@Url.Action("AddAttribute")',
      type: 'POST',
      cache: false,
      success: function (result) {
         // when the AJAX succeeds add result to the table
         $('#AttributesTable').append(result);
      }
   })
}

[HttpPost]
public ActionResult AddAttribute()
{
   var model = new AttributeEntryViewModel();
   return PartialView("_AttributeEntryPartial", model);
}

1 回答

  • 2

    差异的原因与浏览器中的缓存无关。浏览器会将您的 HTML 页面整体缓存而不是其中的一部分(更正确:浏览器不会缓存 HTTP 请求结果的部分内容)

    您的问题是 POST 请求中的值与模型中的值的差异。这在岗位深入解释

相关问题