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>
}
這是偉大的 - 它確實做了驗證 - 有沒有一種方法來使用javascript來查看我的驗證器是否失敗? –
有了JQuery驗證嗎? if($('#id')。valid()){「hello world」;} – Shenaniganz
非常感謝 - 非常感謝。 –