3
Answers

How to assign id to dynamic create textbox In Mvc

Dr.Ajay Kashyap

Dr.Ajay Kashyap

8y
13.6k
1
View:- 
 
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<tr>
@Html.Label("Category Name", htmlAttributes: new { @class = "control-label col-md-2 required" })
</tr>
@if (Model != null && Model.Count > 0)
{
int j = 0;
foreach (var i in Model)
{
<tr style="border:1px solid black">
<td>
@Html.TextBoxFor(a => a[j].Category, new { @class = "form-control", @placeholder = "Enter Category Name", @style = "text-transform: capitalize", @onKeyPress = "return ValidateAlphaComma(event);", @id="Category" })
</td>
<td>
@if (j > 0)
{
<a href="#" class="remove">Remove</a>
}
</td>
</tr>
j++;
}
}
</table>
 
 
 
 
<script language="javascript">
$(document).ready(function () {

//1. Add new row
$("#addNew").click(function (e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
var $trNew = $trLast.clone();

var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
$trNew.find("td:last").html('Remove');
$.each($trNew.find(':input'), function (i, val) {
// Replaced Name
var oldN = $(this).attr('name');
var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
$(this).attr('name', newN);
//Replaced value
var type = $(this).attr('type');
if (type.toLowerCase() == "text") {
$(this).attr('value', '');
}

// If you have another Type then replace with default value
$(this).removeClass("input-validation-error");

});
$trLast.after($trNew);

// Re-assign Validation
var form = $("form")
.removeData("validator")
.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
});

// 2. Remove
$('a.remove').live("click", function (e) {
e.preventDefault();
$(this).parent().parent().remove();
});

});
</script>
Answers (3)
0
Jayant Rajwani

Jayant Rajwani

NA 3.1k 2.5k 8y
i'd suggest you to use some other property with every text box as its id. for example the field name for which you are creating the text box like the value of i can be used by you..
0
Dr.Ajay Kashyap

Dr.Ajay Kashyap

NA 521 289k 8y

Jayant Rajwani sir I am Creating 5 TextBox and it is dynamic created and i want different Id For All Text Box 

0
Jayant Rajwani

Jayant Rajwani

NA 3.1k 2.5k 8y
You can set ID of a textbox like this:

@Html.TextBoxFor(item => item.Category, new { id = "MyId" })

OR

@Html.TextBoxFor(item => item.Category, htmlAttributes: new { id = "MyId" })
This is how your output will look like:
<input ... id="MyId" name="Category" type="text" />