Description:
Controller:
In this example
we explain that how to create Dynamic Textboxes control in Asp.Net MVC.or how
to implement Dynamic Textbox controls with Add Remove button in MVC.or how to
create Dynamic Controls in MVC at runtime in Razor View.
Here we demonstrate
that create dynamic textbox in mvc razor view by click on add remove button
through jQuery.so how to implement Dynamic Textbox controls with Add Remove
button functionality in MVC Razor View.
public class EmployeeController
: Controller
{
// GET: Home
public ActionResult Index()
{
return
View();
}
// POST: Home
[HttpPost]
public ActionResult Index(string[]
DynamicTextBox)
{
JavaScriptSerializer
serializer = new JavaScriptSerializer();
ViewBag.Values =
serializer.Serialize(DynamicTextBox);
string
message = "";
foreach
(string textboxValue in
DynamicTextBox)
{
message += textboxValue + "\\n";
}
ViewBag.Message = message;
return
View();
}
}
View:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Implement
Dynamic TextBox controls with Add Remove Button in ASP.Net MVC</title>
</head>
<body>
@using (Html.BeginForm("Index",
"Employee", FormMethod.Post))
{
<input id="btnAdd" type="button" value="Add" onclick="AddDynamicTextBox()"/>
<br/>
<br/>
<div id="TextBoxContainer">
</div>
<br/>
<input type="submit" value="Submit"/>
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/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", "RemoveDynamicTextBox(this)");
div.append(button);
return
div;
}
function
AddDynamicTextBox() {
var
div = GetDynamicTextBox("");
$("#TextBoxContainer").append(div);
}
function
RemoveDynamicTextBox(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>
0 comments:
Post a Comment