0
因此,我花了最近3天的時間閱讀並搜索此問題的解決方案,但未找到解決方案。所以即時伸出援手。使用Ajax.Beginform進行MVC5部分視圖客戶端驗證驗證不起作用
我有一個非常複雜的視圖有多個部分視圖,但概念很簡單。我點擊一個鏈接到「創建」,它會打開一個由部分視圖填充的引導模式。在這部分視圖中,我使用ajax.beginForm進行發佈。但是,客戶端驗證不起作用。另外,當服務器以modelstate.isvalid作爲false響應時,驗證摘要也不會顯示。下面是代碼...
這是我認爲在模式
@using (Ajax.BeginForm("CreateBox",
new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "myCellarLocations",
OnBegin="ValidateForm",
OnSuccess = "CloseBoxModal"
}))
{
@Html.AntiForgeryToken()
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Create Box</h4>
</div>
<div class="modal-body">
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(a => a.CellarLocationId)
<div class="form-group">
@Html.LabelFor(model => model.DisplayValue, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-7">
@Html.EditorFor(model => model.DisplayValue, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DisplayValue, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" value="Create" class="btn btn-default" />
</div>
}
這裏加載局部視圖是我的控制器代碼
[HttpGet]
[Route("Cellar/CreateBox/{Id?}")]
public ActionResult CreateBox(int id)
{
CreateBoxViewModel model = new CreateBoxViewModel();
model.CellarLocationId = id;
return PartialView("_CreateBox", model);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("Cellar/CreateBox/{Id?}")]
public ActionResult CreateBox(CreateBoxViewModel viewModel)
{
if (ModelState.IsValid)
{
var userId = User.Identity.GetUserId();
//Create Box
Box box = new Box();
box.CellarLocationId = viewModel.CellarLocationId;
box.DisplayValue = viewModel.DisplayValue;
vd.CreateBox(box);
//Get Cellar Locations
List<CellarLocation> model = vd.GetCellarLocationsByUserId(userId).ToList();
return PartialView("_CellarLocations", model);
}
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return PartialView("_CreateBox", viewModel);
}
這裏是腳本在主視圖上
function CloseBoxModal(data) {
alert("close");
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
$('#Box').modal('hide');
}
function ValidateForm() {
alert("here");
return $.validator.unobtrusive.parse($('form'));
}
我的webconfig已經
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
,我有我的包下面包括
bundles.Add(new ScriptBundle("~/bundles/cbt").Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui-{version}.js",
"~/Scripts/jquery.validate*",
"~/Scripts/jquery.unobtrusive*",
"~/scripts/custom-validators.js"));
有人可以告訴我什麼,我做錯了。必須有一種更簡單和更簡潔的方式來對部分視圖窗體進行客戶端驗證並顯示驗證錯誤