-1

I have a form where have a link "Add phone number" on click of this link i want to add textbox upto(15) max dynamically.How to validate this using data annotation to each textbox and save this values of textbox to database?

Do i need to keep 15 entries for all textbox in database?

Chinmay
  • 11
  • 2
  • You should have one model withe property `PhoneNumber` which has data annotation for Max as 15. You bind this property to dynamically added textbox. You retrieve this value and pass it to database on form submission. – Venkata Dorisala Feb 25 '17 at 22:20
  • Refer [this answer](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) for dynamically adding elements. And note the 2nd last code snippet - you need to re-parse the validator –  Feb 26 '17 at 02:54

1 Answers1

0

Model :

Public class UserInfo
{

 //You can have all other form properties here

 [MaxLength(15)]
 [DisplayName("PhoneNumber")]
 public string PhoneNumber {get;set;}

}

Controller :

public ActionResult Add(UserInfo model) {
  If(ModelState.IsValid) {
       Make a database call and pass model to database.
    }
}

View :

@model UserInfo

@{
   ViewBag.Title = "Add User";
   Layout = "~/Views/Shared/_Layout.cshtml";
}
<form method="post" style="margin: 5% 0 0">
  <div class="float-left">
     <p>Name</p>
     <p>Address</p>
     <p>PhoneNumber</p>
  </div>
  <div class="float-right">
     <input type="text" style="margin: 1px 0 2px" name="name" value="@Model.Name" /><br />
     <input type="text" style="margin: 1px 0 2px" name="address" value="@Model.Address" /><br />
     <input type="text" style="margin: 1px 0 2px" name="phonenumber" 
          value="@Model.Address" />
     />
 <br />
     <input type="submit" value="Save" />
  </div>
</form>
Venkata Dorisala
  • 4,783
  • 7
  • 49
  • 90
  • 1
    I think you mis-read how 15 is used. It looks like 15 is not max length of the input box but the maximum number of input boxes for phone numbers – SergGr Feb 26 '17 at 04:38