There's sometimes that you need to add another textbox or other input type for additional information. Ok, say, A Customer can have many Address. As the user completes the form and as he reach the address he can hit the plus sign to add another textbox for another address. So what I did is something like this: (don't know if it's recommended or not)
Html:
<a href="#" class="add-address">Additional Address</a>
<div class="address-container"></div>
JS:
<script>
$(function() {
var i = 0;
var addAddress = function() {
var strBuilder = '<input type="text" name="Addresses[i].Location" />';
$('.address-container').append(strBuilder);
i++;
return false;
};
$('.add-address').click(addAddress);
});
</script>
So my question is:
@Html.EditorFor()?@Html.ValidationMessageFor(), is it possible?I'm using ASP.NET MVC 4; EF Code first approach.
Any help would be much appreciated. Thanks.
Just use i for name attribute.
name="Addresses[' + i + '].Location"
This shoud bind with your model.
var i = 0;
var addAddress = function() {
var strBuilder = '<input type="text" value="" name="Addresses[' + i + '].Location">';
$('.address-container').append(strBuilder);
i++;
return false;
};
See this post which was much useful for me.
Updated
for validation just add this attributes too along with input element.
data-val-email="The Email field is not a valid e-mail address."
data-val="true"
An idea behind this is that, appending correct element with name attribute and validation(data-val="true"). You can see rendered html for already working page where you have used validation.
No, razor works on he server side. Once you're on the client, you don't have access to @Html. This post shows how to model bind with lists, though it looks like you already have a grasp on that with your i iterator.
Generally, I'll have razor produce a mocked Address[0], then copy that generated html into the javascript to generate. It should retain all client-side validation attributes that jQuery looks for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With