In asp.net, you can use asp:Repeater for dynamically generating controls.
for example:
<asp:Repeater runat="server" id="rpt">
<ItemTemplate>
<asp:Textbox runat="server"/>
</ItemTemplate>
</asp:Repeater>
Then you can get loop through the items on the server side:
foreach(var items in rpt.Items)
{
}
And in MVC, you can do something like this:
@foreach(var item in model)
{
@Html.TextBoxFor(a=>item.searchCriteria);
}
But there is a problem:
I would like to generate textboxes when ever user clicks add more textbox button:
If I use foreach in MVC, then I won't be able to fetch the user input on the controller, also, I don't have a model to loop through.
And the final desired output will be:
After the user clicks the "Add more textbox" button, a new textbox will be append to the bottom, and after the user clicks the search button, the text inside the textbox will be generated into a query string, something like this:
View:
<input name="searchCriteria" type="text" class="form-control" />
<input name="searchCriteria" type="text" class="form-control" />
<input name="searchCriteria" type="text" class="form-control" />
<input name="searchCriteria" type="text" class="form-control" />
Controller:
public ActionResult Search()
{
string queryString = Request.RawUrl;
//parse the querystring here
return View(NumberOfVisitorsReport);
}
And the query string generated will be:
www.website.com/?searchCriteria=a&searchCriteria=b&searchCriteria=c
So are there any alternative way to achieve this in MVC?
Edit:
I've took a look at some post on "How to generate controls dynamically in MVC"
For example
Control creation based on model value in MVC4
He is generating controls based on value in database, if I implement this to my website, the controls will lose value on each post back.