I have read a lot about how to validate dynamically generated content in mvc 3.0 such as the one xhalent has written , But I cant understand how to use it in my code. I mean it does not work for dynamically generated form elements. Here is my Model classes:
public class Person
{
[Required]
public string Name { get; set; }
[Required]
public string Phone { get; set; }
public IList<Address> Addresses{get;set;}
public Person()
{
Addresses = new List<Address>()
{
new Address(){Street="1"},new Address(){Street="2"}
};
}
}
public class Address
{
[Required(ErrorMessage="Error")]
public string Street { get; set; }
}
And this the view in which the form is begin displayed:
<script src="<%: Url.Content("~/Scripts/jquery-1.5.1.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>"
type="text/javascript"></script>
<% using (Html.BeginForm())
{ %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Person</legend>
<%: Html.EditorForModel() %>
<div class="phone-numbers">
<%
foreach (var item in Model.Addresses)
{
%>
<%Html.RenderPartial("EditorTemplates/Addresses", item);%>
<%} %>
</div>
<div style="padding: 10px 0px 10px 0px">
<a id="add-phone" href="javascript:void(0);">Add another</a>
</div>
<input type="submit" value="Create" />
</fieldset>
<% } %>
</div>
$().ready(function () {
$("#add-phone").click(function () {
$.ajax({
url: '<%: Url.Action("GetNewAddress") %>',
success: function (data) {
$(".phone-numbers").append(data);
}
});
});
});
And this is the partial view for Address:
<div style="padding: 5px 0px 5px 0px" name="editorRow" id="editorRow">
<%: Html.LabelFor(m => m.Street) %>
<%: Html.EditorFor(m => m.Street)%>
<%:Html.ValidationMessageFor(m=>m.Street) %>
</div>