Validate only ajax loaded partial view

故事扮演 提交于 2019-12-12 04:14:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!