Dynamically add controls when a button is clicked in asp.net mvc

I am creating an asp.net MVC application in which I want to provide functionality for adding controls dynamically. I have a form in which there are 2 text boxes for the first and last name that serve as one control. The user can now add any number of this group of controls. I can add these controls to the page using java script. But I do not know how to access the values โ€‹โ€‹of these controls when the user submits.

Please help with this or suggest a different approach.

thanks

+4
source share
3 answers

Read the article Editing a Variable Length List, ASP.NET MVC 2-style by Steve Sanderson. It shows how to do what you are looking for in a pure MVC style.

+2
source

Look at using a jQuery AJAX call for a submit operation.

You can interact through your controls (easily using the jquery and $ .each class selector) and drag and drop variables into js variable. Parse it as JSON and pass the data back to the controller using ajax call ..

+2
source

If you're looking at webforms, you're used to adding these new controls programmatically to your code. Using ASP.NET MVC, you better do this with javascript.

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

You can also iterate over a number in a hidden field called "txtNumFields" and then use this as your control 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()]; ... } 
+1
source

Source: https://habr.com/ru/post/1306693/


All Articles