3

I have the following data model

public class User
{
        [Required(ErrorMessage = "First name required!")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Last name required!")]
        public string LastName { get; set; }
}

I have the following view called "UserForm" that uses the above model

@model User
@using (Html.BeginForm("myAction", "MyController"))
{
@Html.TextBoxFor(model => model.FirstName)
@Html.TextBoxFor(model => model.LastName)
@Html.ValidationSummary()
<input type="submit" value="Save" />
}

I have tested the above code and unobtrusive validation and form posts work correctly and without any issues. However, if I include the above view as a partial view in a second view as shown below, then client side unobtrusive validation stops working.

<div id="myPartialView">
<!-- Include form as partial view -->
@{Html.RenderAction("myAction", "MyController");}
</div>

I tried explicitly reloading unobtrusive validation using the following line of javascript

jQuery.validator.unobtrusive.parse('#myPartialView');

Now validation is working but I am unable to submit the form. I used fiddler and I can see that clicking on the submit button is not triggering any activity. Any thoughts on what I may be doing wrong?

  • 4
    do you try using @Html.Partial("UserForm", yourUserModel) to include form ? – Mate Dec 08 '12 at 05:35
  • Mate - I tried @Html.Partial on your suggestion but I am seeing the same problem. No client side validation and no activity when form submit is clicked –  Dec 08 '12 at 05:49
  • 1
    do you could add a part of the HTML rendering? I tried an example as yours, and it works. Maybe can be helpful http://stackoverflow.com/questions/4406291/jquery-validate-unobtrusive-not-working-with-dynamic-injected-elements/5783020#5783020 – Mate Dec 08 '12 at 06:36
  • @Mate - Thanks for the help! The problem was with me and not with the partial view. I have posted my answer below. –  Dec 08 '12 at 18:21

1 Answers1

2

For anyone stumbling across this question, I have this issue resolved now. My forms were embedded in a Jquery Modal box and I had an invalid html tag. This was not causing the modal to stop working but was stopping my form from submitting. (I am still not sure why). I found this error using the excellent html validator from w3c

http://validator.w3.org

It should be noted that I still need

jQuery.validator.unobtrusive.parse('#myPartialView');

to get client side validation to work for dynamic content. This is a well known issue which is discussed in more detail in the link posted by @Mate above