Turi
Turi

Reputation: 171

MVC Best way to get values in controller of dynamically Textboxes

I want to create a Poll view where the users can enter the name of the poll and the options. But at the beginning I don't know how many options the users will enter.

I'm thinking about having a textbox and a button to create another textbox.

My problem is that I don't know how to get the value of this new textbox.

What is the best way?

I thought of creating an @Html.HiddenFor(x => x.PollOptionsStr) with all values separated by comma and populating it with jQuery, but I don't know if this is the best option.

Upvotes: 0

Views: 1083

Answers (1)

mahlatse
mahlatse

Reputation: 1307

Assuming that your model is

public class PollModel
{
    public string PollName{get;set;}
    public List<string> PollOptions{get;set;}
    public int MaxPollStars{get;set;}
}

Then your post method will expect a PollModel

[httpPost]
[ValidateAntiForgeryToken]
public ActionResult DynamicPoll(PollModel model)
{
   foreach(var item in model.PollOptions)
   {
      ///do something to each poll option
   }
}

you can map the dynamicly created poll options using JS to create an element that has structure

name="PollOptions"

Upvotes: 1

Related Questions