Ashwani K
Ashwani K

Reputation: 7990

Add controls dynamically on button click in asp.net mvc

I am creating an asp.net MVC application in which I want to provide a functionality to add a controls dynamically. I have a form in which there are 2 text boxes for First Name and Last name which serve as a single control. Now an user can add any number of this group of controls. I am able to add these controls on the page using java script. But I do not know how to access the values of these control when the user submits.

Please help in this or suggest another approach

Thanks

Upvotes: 4

Views: 11983

Answers (3)

Dan Diplo
Dan Diplo

Reputation: 25339

Have a read of the article Editing a variable length list, ASP.NET MVC 2-style by Steve Sanderson. It shows you how to do what you are looking for in a clean, MVC style.

Upvotes: 1

GordonBy
GordonBy

Reputation: 3397

Look at using a Jquery AJAX call for the submit operation.

You can interate through your controls (easy with jquery class selector and $.each) and push the variables into a js variable. Parse it as JSON and pass the data back to the controller using the ajax call..

Upvotes: 2

Dave Swersky
Dave Swersky

Reputation: 34810

If you're coming from a webforms perspective, you're accustomed to adding those new controls programmatically in the codebehind. Using ASP.NET MVC, you're better off doing this with javascript.

It should be trivial to write a javascript function that adds FirstName1, FirstName2, FirstName3, etc. In the Controller, inspect the Request.Form.AllKeys to determine how many fields were added by the user.

You could also iterate a number in a hidden field called "txtNumFields", then use that as your controlling value in a for loop:

int numFields = int.Parse(Request.Form["txtNumFields"]);
for (i==0;i<numFields ;i++)
{
   string firstName = Request.Form["FirstName" + i.ToString()];
   ...
}

Upvotes: 1

Related Questions