In this article I will explain with an example, how add dynamic
TextBoxes and also Save (Insert) the values of dynamic TextBoxes to Database in
ASP.Net MVC Razor.
The dynamic
TextBox controls with
Add Remove Button functionality will be created on Client Side using
jQuery in
ASP.Net MVC Razor.
Database
I have made use of the following table Names with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
Namespaces
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This Action method gets called when the Form is submitted due to the click of the Submit button. The values of the dynamic TextBoxes are received through the DynamicTextBox string array.
Note: The values are received as array because all the dynamic TextBoxes are set with same Name attribute.
The values of received string array is serialized into a
JSON string using
JavaScriptSerializer and then the
JSON string is assigned to a
ViewBag object named
Values for recreation of dynamic
TextBoxes after Form submission is completed.
Then a loop is executed and all the values of the Dynamic TextBoxes are extracted and inserted into Database Table.
Finally, total count of the records inserted into Database Table is assigned to a
ViewBag object named
Message which is later displayed using
JavaScript Alert Message Box after Form Submission is completed.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
// POST: Home
[HttpPost]
public ActionResult Index(string[] DynamicTextBox)
{
//Serialize the Array and assign to ViewBag.
JavaScriptSerializer serializer = new JavaScriptSerializer();
ViewBag.Values = serializer.Serialize(DynamicTextBox);
//Loop through the dynamic TextBox values.
foreach (string textboxValue in DynamicTextBox)
{
//Insert the dynamic TextBox values to Database Table.
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Names(Name) VALUES(@Name)"))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", textboxValue);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
//Set the Message to be displayed later in View.
ViewBag.Message = DynamicTextBox.Count() + "records saved.";
return View();
}
}
View
The following View consists of an
HTML Form which posts to the
Index action method discussed earlier. The Form consists of the following elements: -
1.
Add Button – This Button makes call to the
AddTextBox JavaScript function which dynamically creates an
HTML DIV with a
TextBox and a Button for removing the
TextBox and appends it to the
TextBoxContainer HTML DIV.
2.
TextBoxContainer – This
HTML DIV is used for holding the Dynamic TextBoxes.
3.
Submit Button – This
Button is used for submitting the
HTML Form.
Adding Dynamic TextBoxes
When the
Add button is clicked, the
GetDynamicTextBox JavaScript function is called which returns an
HTML DIV consisting of a
TextBox and a
Remove Button.
Removing Dynamic TextBoxes
When the
Remove Button is clicked, the respective parent
HTML DIV element is removed from the
TextBoxContainer HTML DIV.
Recreating dynamic TextBoxes after Form Submission
When the page reloads after Form Submission, the values of the dynamic
TextBoxes are fetched from the
Values ViewBag object and using loop one by one a dynamic
TextBox is created and added to the
TextBoxContainer HTML DIV.
Displaying the values of dynamic TextBoxes after Form Submission
The
Message ViewBag object consists of the concatenated string message sent from the Controller. The value of the
Message ViewBag object is displayed then using
JavaScript Alert Message Box.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style>
#TextBoxContainer input {margin: 0 5pt 5pt 0; }
</style>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<input id="btnAdd" type="button" value="Add" onclick="AddTextBox()" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input type="submit" value="Submit" />
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
function GetDynamicTextBox(value) {
var div = $("<div />");
var textBox = $("<input />").attr("type","textbox").attr("name", "DynamicTextBox");
textBox.val(value);
div.append(textBox);
var button = $("<input />").attr("type","button").attr("value", "Remove");
button.attr("onclick","RemoveTextBox(this)");
div.append(button);
return div;
}
function AddTextBox() {
var div = GetDynamicTextBox("");
$("#TextBoxContainer").append(div);
}
function RemoveTextBox(button) {
$(button).parent().remove();
}
$(function () {
var values = eval('@Html.Raw(ViewBag.Values)');
if (values != null) {
$("#TextBoxContainer").html("");
$(values).each(function () {
$("#TextBoxContainer").append(GetDynamicTextBox(this));
});
}
});
</script>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
$(function () {
alert("@ViewBag.Message")
});
</script>
}
</body>
</html>
Screenshots
Dynamic TextBoxes
Values of dynamic TextBoxes saved in database Table
Downloads