I have a form in which the TextBox is dynamically populated. The user has the flexibility to add and remove TextBox which is done using JQuery. I would need to pass the value of TextBox to my Controller on Submit.
This is my View.
@using (Html.BeginForm("Controller", "Admin", FormMethod.Post, new { required = "required" }))
{
<h4>Add new Q&A</h4>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<input type="text" name="Question" id="Question" required placeholder="Question 1" class="form-control" /><br />
</div>
</div>
<input type="button" name="Add" id="Add" value="Add" class="btn btn-success" />
<input type="button" name="Remove" id="Remove" value="Remove" class="btn btn-danger" /> <br /><br />
<textarea rows="5" name="Answer" id="Answer" placeholder="Answer" required class="form-control"></textarea><br />
@Html.DropDownList("Intent", ViewData["Intent"] as List<SelectListItem>, "Select Intent", new { @class = "form-control", required = "required" })
<br /><input type="text" name="PrimaryEntity" id="PrimaryEntity" placeholder="Primary keyword" required class="form-control" /><br />
<input type="text" name="SecondaryEntity" id="SecondaryEntity" placeholder="Secondary keyword (optional)" class="form-control" /><br />
<input type="submit" name="Submit" id="Submit" class="btn btn-success" />
}
This is how my JS looks
$(document).ready(function () {
var counter = 2;
$("#Add").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<input type="text" name="textbox' + counter +
'" id="Question' + counter + '" value="" class="form-control" required placeholder="Question ' + counter +
'"> <br />');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#Remove").click(function () {
if (counter == 2) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
Sorry if I sound lame. Just getting started with MVC!