2012-08-30 24 views
0

我在這裏有一個簡單的例子。基本上是一個表單提交時將通過ajax請求重新加載自己。問題是,當這種情況發生時,不顯眼的JavaScript不再有效。我想我可以添加驗證和不顯眼的文件在我從ajax調用返回的html中,但是必須有更簡單的方法來重新驗證驗證器,不是嗎?不顯眼的Javascript - 和Ajax請求

注意我正在劫持我的submit按鈕,以便從ajax請求返回的html中執行一個AJAX請求,它將替換dom中的表單。

型號:

public class Foo 
    { 
     public int Bar { get; set; } 
    } 

控制器:

public class FooController : Controller 
{ 

    public ActionResult Index() 
    { 
     return View(new Foo{}); 
    } 

    [HttpPost] 
    public ActionResult Form(Foo model) 
    { 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(Foo model) 
    { 
     return View(); 
    } 

} 

Index.cshtml

@model PartialPostBackValidation.Models.Foo 

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>@Html.ActionLink("Index", "Index")</h2> 
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

<script> 
    $(function() { 
     $("body").on("click", ".ajax-submit", function() { 
      var form = $(this).parents("form"); 
      $.post(
       form.attr("action"), 
       form.serialize(), 
       function (html) { 
        form.replaceWith(html); 
       } 
      ); 
      return false; 
     }); 
    }); 
</script> 


@{Html.RenderPartial("Form");} 

Form.cshtml

@model PartialPostBackValidation.Models.Foo 

@{ 
    ViewBag.Title = "Index"; 
    Layout = null; 
} 

@using (Html.BeginForm("Form", "Foo")) { 
    @Html.ValidationSummary(true) 
    <fieldset> 
     <legend>Foo</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Bar) 
     </div> 
     <div class="editor-field"> 
      @Html.TextBoxFor(model => model.Bar) 
      @Html.ValidationMessageFor(model => model.Bar) 
     </div> 
     <p> 
      <input type="submit" value="Create" class="ajax-submit" /> 
     </p> 
    </fieldset> 
} 

回答

2

要得到驗證工作,你只需在表格上重新啓用了一次內容是動態加載:

$('#form-id').removeData('validator'); 
$('#form-id').removeData('unobtrusiveValidation'); 
$.validator.unobtrusive.parse('#form-id'); <<<<<< Just having this could be enough but some people complain that without removingData first it doesn’t always work. 

附:當然,你將需要添加一個id屬性到你的@using (Html.BeginForm("Form", "Foo"))

+0

這是偉大的 - 它確實做了驗證 - 有沒有一種方法來使用javascript來查看我的驗證器是否失敗? –

+0

有了JQuery驗證嗎? if($('#id')。valid()){「hello world」;} – Shenaniganz

+0

非常感謝 - 非常感謝。 –