代码之家  ›  专栏  ›  技术社区  ›  Bryan Roth

ASP.NET MVC:如何使用指定的updateTargetID验证Ajax表单?

  •  2
  • Bryan Roth  · 技术社区  · 16 年前

    我正在尝试解决在用户提交一个Ajax表单后如何显示验证错误 UpdateTargetID 属性集。

    我无法理解如何用验证错误更新Ajax表单,而不返回 Create 部分视图 results 如果表单有效,则应返回 Records 局部视图。

    创建.ascx

    <%  Using Ajax.BeginForm("Create", 
                             "Record", 
                             New Record With {.UserID = Model.UserID}, 
                             New AjaxOptions With {
                                 .UpdateTargetId = "results", 
                                 .LoadingElementId = "loader"
                             })%>        
        Date Located
        <%= Html.TextBoxFor(Function(model) model.DateLocated)%>
        <%= Html.ValidationMessageFor(Function(model) model.DateLocated) %>
    
        Description
        <%= Html.TextBoxFor(Function(model) model.Description)%>
        <%= Html.ValidationMessageFor(Function(model) model.Description) %>
    
        <input id="btnSave" type="submit" value="Create" />          
    
        <span id="loader" class="loader">Saving...</span>
    <%End Using%>
    

    记录.ascx

    <div id="results">
        ...
    </div>
    

    记录控制器.vb

    Function Create(ByVal newRecord As Record) As ActionResult
        ValidateRecord(newRecord)
    
        If Not ModelState.IsValid Then
            Return PartialView("Create", newRecord)
        End If
    
        _repository.Add(newRecord)
        _repository.Save()
    
        Dim user = _repository.GetUser(newRecord.UserID)
        Return PartialView("Records", user)
    End Function
    
    1 回复  |  直到 15 年前
        1
  •  3
  •   Community Mohan Dere    9 年前

    如果不刷新包含带有验证消息的元素(在本例中是表单)的DOM部分,则无法显示验证错误。所以您可以将整个表单和结果DIV放在一个将被刷新的部分中。你可以看看 this post 也。