Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc 3.0 client validation not working

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.

like image 844
user979189 Avatar asked Feb 23 '23 19:02

user979189


1 Answers

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.

like image 108
Darin Dimitrov Avatar answered Feb 25 '23 07:02

Darin Dimitrov