Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add @html tags using javascript?

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:

  1. It is possible to add the textbox as this @Html.EditorFor()?
  2. It would really be great if I can also add in the @Html.ValidationMessageFor(), is it possible?

I'm using ASP.NET MVC 4; EF Code first approach.

Any help would be much appreciated. Thanks.

like image 629
Boy Pasmo Avatar asked May 10 '26 07:05

Boy Pasmo


2 Answers

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.

like image 142
Ashwini Verma Avatar answered May 11 '26 22:05

Ashwini Verma


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.

like image 26
Jonesopolis Avatar answered May 11 '26 22:05

Jonesopolis