问题
I have a form with some controls. There is a button on the form which loads a partial view. Inside the partial view, there are two required field textboxes along with a button. And when its clicked, I need to display error messages only for textboxes which are inside the partial view, but not for the fields in the actual form. And when I click form's submit button, all error messages must show up.
After partial view is loaded, I am re-initializing the validation plugin as below.
$('#test').removeData("validator");
$.validator.unobtrusive.parse('#test');
I tried using validation attribute described in below thread but its not working. Maybe it works for normally loaded views.
ASP.NET MVC Validation Groups?
However, I can validate individually by calling textbox1.valid() and textbox2.valid(). But I think I am missing standard way of doing it. Any help is appreciated.
回答1:
you can do this by submitting your partial view using Ajax.BeginForm()
//In Partail View
@model SomeModel
@using (Ajax.BeginForm("SomeActionName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "targetId"})) {
@Html.EditorFor(mode=>model.FirstText)
@Html.EditorFor(mode=>model.SecText)
<input type="submit" value="save">
}
//In Controller
public ActionResult SomeAction(SomeModel model)
{
return PartaiulView(model);
}
here you can validate your Partial View NOTE: when you submit you form using Ajax.BeginForm you must specify "UpdateTargetId" where your result will be appear on View.
//In View
<div id="targetId">
@Html.Partail("PartialView")
</div>
OR if you want to Redirect to another action if your model is valid then modified your action
public ActionResult SomeAction(SomeModel model)
{
if(ModelState.IsValid)
{
return Json(new {redirect = @Url.Action("SomeAction","SomeController")})
}
return PartaiulView(model);
}
then in partail view you can invoke OnSuccess method of Ajax.BeginForm
@using (Ajax.BeginForm("SomeActionName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "targetId",OnSuccess="success"}))
{
}
<script type="text/javascript">
function success(data)
{
if(data.redirect)
{
windows.location = data;
}
}
</script>
check both way which one is suitable to you.
来源:https://stackoverflow.com/questions/12613188/validate-only-ajax-loaded-partial-view