0

I have read many post but unable to resolve my issue.

I have a view which has add button on its click i am showing partial view, that partial view has a form for adding records, which is not validating client side. i am using jquery validation and i have added js files in main view in which partial view is opening.

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>

<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

My View:

 <div id="Div1">
   <a id="lnkAdd">
      <div>Add</div>
   </a>
 </div>

$("#lnkAdd").click(function () {
       $.ajax({
            url:  '@Url.Action("MethodName", "ControllerName")',
       type: "POST",
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
    }).done(function () {
    }).success(function (dv) {
        $("#Div1").html(dv);
    })
    });

Controller:

[Authorize]
    public PartialViewResult MethodName()
    {
        return PartialView("_PartialViewName");
    }

Parital View:

<div id="UsersDiv">

<div class="grid-background" style="border: 1px solid #8dc2f5;">

    @using (Html.BeginForm("AddRecord", "ControllerName"))
    {
      <div class="form-bg" style="border: 0px; margin-top: 0px; width: 966px;">
     <div class="form-field-bg">
      @Html.LabelFor(m => m.FirstName)
      @Html.TextBoxFor(m => m.FirstName, new { @class = "label-class" })
      @Html.ValidationMessageFor(m => m.FirstName, "", new { @class = "validation-class" })
    </div>

  <input type="submit" value="Save" id="btnSaveUsers" name="AddRecord" class="signup-button" />
     }

1
  • I am not sure if you can write both done and success !!! Commented Jun 20, 2013 at 8:21

4 Answers 4

2

The validators are only wired up when the document.ready event is triggered, for dynamic content, you have to manually trigger them.

Change your success handler to this:

.success(function (dv) {
    $("#Div1").html(dv);

    $("form").data("validator", null);
    $.validator.unobtrusive.parse($("form"));
})
Sign up to request clarification or add additional context in comments.

1 Comment

it gives me error Uncaught TypeError: Cannot read property 'unobtrusive' of undefined in chrome.
1

You can validate model on server side and append errors on client side

 public PartialViewResult _CreateSupplier()
        {
            return PartialView(new Supplier());
        }

    [HttpPost]
    public JsonResult _CreateSupplier(Supplier model)
    {
    //Validation
    return Json(new
                    {
                        status = transactionStatus,
                        modelState = ModelState.GetModelErorrs()
                    }, JsonRequestBehavior.AllowGet);
    }

Form post jquery method

$('#create-supplier').submit(function (e) {
    e.preventDefault();
    var $form = $(this);
    if (!ModelIsValid($form))
        return;
    AjaxPost($form.serialize(), '@Url.Action("_CreateSupplier")', function (result) {
        if (result.status == 0) {
            $form[0].reset();
            //Success
            var grid = $("#gridSupplier").data("kendoGrid");
            grid.dataSource.read();
        } else if (result.status == 1)
            AddFormErrors($form, result);
        else if (result.status == 2)
           //error;
    });
});

Checking model method is valid and if invalid adding errors to form

function ModelIsValid(form) {
    var validator = $(form).validate(); // obtain validator
    var anyError = false;
    form.find("input").each(function () {
        if (!validator.element(this)) { // validate every input element inside this step
            anyError = true;
        }
    });

    if (anyError)
        return false; // exit if any error found    
    return true;
}

function AddFormErrors(form, errors) {
    for (var i = 0; i < errors.modelState.length; i++) {
        for (var j = 0; j < errors.modelState[i].errors.length; j++) {
            var val = $(form).find("[data-valmsg-for='" + errors.modelState[i].key + "']");
            if (val.html().length > 0) {
                $(form).find("[for='" + errors.modelState[i].key + "']").html(errors.modelState[i].errors[j]);
            } else {
                val.html('<span for="' + errors.modelState[i].key + '" generated="true" class="" style="">' + errors.modelState[i].errors[j] + '</span>');
            }
        }
    }
}

Ajax post method:

function AjaxPost(postData, url, callback) {
    $.ajax({
        url: url,
        type: 'POST',
        data: postData,
        dataType: 'json',
        success: function (result) {
            if (callback) callback(result);
        }
    });
}

And last c# extension method which checks returns model state errors

 public static IEnumerable<object> GetModelErorrs(this ModelStateDictionary modelState)
        {
            return modelState.Keys.Where(x => modelState[x].Errors.Count > 0)
                .Select(x => new {
                 key = x,
                 errors = modelState[x].Errors.Select(y => y.ErrorMessage).ToArray()
                });
        }

Comments

0

Did you include the jQuery file?

<script src="@Url.Content("~/Scripts/jquery-2.0.0.min.js")" type="text/javascript"></script>

Comments

0

I fixed adding the code below after rendering the partial

@Scripts.Render("~/bundles/jqueryval")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.