代码之家  ›  专栏  ›  技术社区  ›  Michael Wallasch

如果ModelState无效,则为ASP.NET MVC AJAX更改updateTargetID

  •  1
  • Michael Wallasch  · 技术社区  · 17 年前

    我使用一个有两个局部视图的视图。

    <div id="matches">
        <% foreach (var item in Model)
           { %>
        <% Html.RenderPartial("RenderMatchesListRowUserControl", item); %>
        <% } %>
    </div>
    <div id="addMatchFormBox">    
        <% Html.RenderPartial("AddNewMatchUserControl");%>
    </div>
    

    第一个部分视图“renderMatcheslistrowUserControl”呈现简单的DIV元素(对于匹配列表),第二个部分视图“addNewMatchUserControl”呈现表单以在列表下创建新的匹配:

    AddNewMatchUserControl的源:

    <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
    
    <% using (Ajax.BeginForm("Create", new AjaxOptions
       {
           UpdateTargetId = "matches",
           InsertionMode = InsertionMode.InsertAfter,
           OnSuccess = "flashit",
           OnFailure = "renderForm"
       }))
       {%>
    <fieldset>
        <legend>New Match</legend>
        <p>
            <label for="DurationBetweenMovesInDays">
                Dauer (in Tagen) zwischen den Z&uuml;gen:</label>
            <%= Html.TextBox("DurationBetweenMovesInDays")%>
            <%= Html.ValidationMessage("DurationBetweenMovesInDays", "*")%>
        </p>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
    <% } %>
    

    根据模型状态,控制器返回新匹配项的部分视图或表单的部分视图,以显示模型错误。

    if (Request.IsAjaxRequest()) {
                return ModelState.IsValid ?    PartialView("RenderMatchesListRowUserControl", match) : PartialView("AddNewMatchUserControl");
            }
    

    它可以正常工作,直到模型状态变为无效。在这种情况下,表单将呈现在匹配项列表的末尾,因为updateTargetID引用了包含匹配项列表的DIV元素。要避免这种情况,必须更改updateTargetID以引用包含表单的DIV元素。但我不知道该怎么做。

    2 回复  |  直到 17 年前
        1
  •  0
  •   wut-excel    7 年前

    我也有同样的问题。如果模型状态无效,我希望更新包含表单的DIV中的内容,如果成功保存,则更新数据集合。所以我使用的技巧不是使用“updateTargetID”。我使用“onSuccess”来处理它。

    下面是一个例子。

        @using (Ajax.BeginForm("SaveUser", new AjaxOptions{
    HttpMethod = "Post",
    LoadingElementId = "save-progress",
    OnSuccess = "onUpdateSuccess"
    InsertionMode = InsertionMode.Replace}))
    

    下面是一个javascript示例。

    function onUpdateSuccess(response, xhr) {
         $('#progress-bar').css({ 'display': 'none' });
         if (response.indexOf('form') != -1) {
            $('#addOrEditUserForm').html(response);
    
         } else {
           $('#user-table').html(response);
           $('#addOrEditUserForm').html('')
     }
    

    };

        2
  •  -2
  •   Leniel Maccaferri    15 年前

    可以。没有办法以这种方式实现这一目标。我用jquery解决了它。