4

This is the code in my partial view -

@using (Ajax.BeginForm("SaveLayout", new AjaxOptions { HttpMethod = "Post"}))
{
@Html.ValidationSummary(true)
<div style="padding: 10px;">
    <div class="editor-field">
        Layout Name: @Html.EditorFor(m => m.Name)
        @Html.ValidationMessageFor(m => m.Name)</div>
    <br />
    <br />
    <input type="submit" value="Save" />
    <input type="button" onclick="CloseDialog()" value="Cancel" />
</div>
}

in my _Layout.cshtml looks like this -

<script src="@Url.Content("~/Scripts/JQuery/jquery-1.6.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/JQuery/jquery-ui.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/JQuery/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/JQuery/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/JQuery/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

i have this in my root web.config -

<add key="ClientValidationEnabled" value="true"/> 
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

this is how my controller action looks like -

[HttpPost]
public ActionResult SaveLayout(Model.Layout layout)
{
    if (ModelState.IsValid)
    {
        ILayout.SaveLayout(layout);
    }
    return PartialView("_SaveLayout", layout);
}

and rouhgly this is my model -

public class Layout : BaseModel
{
    [Required(ErrorMessage = "Please assign name to the compare group.")]
    public string Name { get; set; }
}

I cannot get my client side validation working when the name field is empty and user hits save button. Could someone please suggest what am i doing wrong here? Any help would be greately appreciated.

1 Answer 1

8

Once you update the DOM with a new contents of the form client validation stops working because all event handlers that it initially attached die. Here's a blog post that you may take a look at which explains how to reattach client validation in dynamically loaded contents.

Basically you have to use the $.validator.unobtrusive.parse method in your AJAX success callbacks when updating the DOM in order to reattach client validation.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. could you please let me know what do you mean by "dynamic contents"?
@user979189, anything that is inserted into the DOM which was not initially part of it when the page was loaded. For example in your case this is the html in your partial view.

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.