4

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

3 Answers 3

2

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..

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

are there any newer, more efficient solutions, given it's been 4 years??
1

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()];
   ...
}

4 Comments

Thanks Dave, I tried this approach but Request.Form.AllKeys is always 0. It is not showing any control which I added using javascript. Any help?
This is the problem, as Request.Form.AllKeys.Count is always 0. So I am not able to access any item in my controller.
Are you setting an id on each form field? You also need to make sure the button is of type=submit, and the Action needs to be able to accept a POST (decorate the Action method with [HttpPost]
Actually I have a div with two text boxes which is inside a main div. Using jQuery I am cloning this child div and adding to the main div, each time the user is clicking "Add one more" button. Yes, button is of submit type.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.