0

I have a Form which will dynamically add textboxes for a particular database field. I wanted to use Model Binding to retrieve values from the Form on a Controller. I know Model Binding uses the textbox's id to retrieve values. However it's never recommended to have multiple textboxes with same ID as its unique. I have it such that in case a user needs more textboxes for the same field, they can add them dynamically by clicking a button. How do I retrieve values from these textboxes? Is there a way I can use html classes with model binding to retrieve the values instead? Or should I do it like this

       public ActionResult MyAction(FormCollection form)
        {
   // ModelBinder will set "form" appropriately
      foreach(var value in form.Getvalues("duplicatedFieldId"))
         {
          //do something with value
         }
        }

Regards

9
  • Model binding does not use a controls id attribute, it uses a controls name attribute. What is the model you want to bind to (a simple array of string or a collection of complex objects)?
    – user3559349
    Mar 21, 2015 at 11:05
  • I want to pass an array of string items retrieved from the textboxes. Can I give the textboxes the same name then iterate through them and retrieve there values?
    – Dev
    Mar 21, 2015 at 12:21
  • Give each textbox the same name attribute (say <input type="text" name="myName" />) and then post to public ActionResult MyAction(string[] myName) { (or List<string> myName) then you can loop through the values. Note duplicate id attributes are invalid html but duplicate name attributes are fine.
    – user3559349
    Mar 21, 2015 at 12:26
  • If you have added the previous comment as an answer, then I would have marked it as an answer. If you do so I'll make it for an answer for users who will view this later on.
    – Dev
    Mar 21, 2015 at 12:51
  • @Stephen so ideally this should work ` public ActionResult MyAction(FormCollection form) { List<string> emailList = new List<string>(); foreach(var value in form.GetValues("TeamLeader")) { emailList.Add(value) } }`
    – Dev
    Mar 21, 2015 at 13:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.