If I misunderstood anything, could you provide more details, mainly including : relevant sample code, how to test the code and the problems encountered.
Best regards,
Xudong Peng
ASP.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today. Learn more >
Thank you very much for your reply, in my case my model has a master "BidGroupList" and child "BidSubmissionList" array, for that am using the below script to change the second index in the array
I think I may have misunderstood what you mean. I recreated an example to test your code, and modified some of the code to fix the problem.
<form asp-action="AuctionMaterials" id="my-form">
<div>
<h4>Material Auction</h4>
<hr />
@if (Model.BidGroupsList.Count() > 0)
{
@for (int CategoryIndex = 0; CategoryIndex < Model.BidGroupsList.Count(); CategoryIndex++)
{
@*<input type="hidden" asp-for="@Model.ID" />*@
<table class="table">
<thead>
<tr>
<th class="cell">
@Html.DisplayNameFor(model => model.BidGroupsList[0].AuctionMaterials[0].Container)
</th>
</tr>
</thead>
<tbody>
@for (int AuctionMaterialsIndex = 0; AuctionMaterialsIndex < Model.BidGroupsList[CategoryIndex].AuctionMaterials.Count(); AuctionMaterialsIndex++)
{
<tr>
<td>
@Html.DisplayFor(model => Model.BidGroupsList[CategoryIndex].AuctionMaterials[AuctionMaterialsIndex].Container)
</td>
</tr>
}
</tbody>
</table>
<div>
<table class="table">
<thead>
<tr>
<th class="cell ">
@Html.DisplayNameFor(model => model.BidGroupsList[0].BidSubmissionList[0].BidPrice)
</th>
</tr>
</thead>
<tbody>
@for (int BidSubmissionIndex = 0; BidSubmissionIndex < Model.BidGroupsList[CategoryIndex].BidSubmissionList.Count(); BidSubmissionIndex++)
{
<tr>
<td>
<input asp-for="@Model.BidGroupsList[CategoryIndex].BidSubmissionList[BidSubmissionIndex].BidPrice" class="form-control" />
<span asp-validation-for="@Model.BidGroupsList[CategoryIndex].BidSubmissionList[BidSubmissionIndex].BidPrice" class="text-danger"></span>
</td>
</tr>
}
</tbody>
</table>
<input type="button" id="add" class="btn btn-primary AddButton" value="Add" />
</div>
}
}
</div><br />
<input type="submit" name="subBtn" value="Submit" class="btn btn-primary" />
</form>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$(".AddButton").each(function (index) {
$(this).on("click", function () {
var parentElement = $(this).parent();
var $TableBody = parentElement.find('table').find('tbody');
var $trLast = $TableBody.find("tr:last");
var NumberOfRows = $TableBody.find('tr').length;
var $trNew = $trLast.clone();
var LastIndexForSuffix = $trNew.find(':input:first').attr('name').lastIndexOf('[');
var suffix = $trNew.find(':input:first').attr('name').substr(LastIndexForSuffix).match(/\d+/);
var index = '';
$.each($trNew.find(':input'), function (i, val) {
// Replaced Name
//console.log($(this))
var oldName = $(this).attr('name');
var oldNameSuffixName = oldName.substr(oldName.indexOf('.'));
var newNameSuffixName = oldNameSuffixName.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
var newName = oldName.replace(oldNameSuffixName, newNameSuffixName);
$(this).val('');
index = parseInt(suffix) + 1;
$(this).attr('name', newName);
$(this).next('span').attr('data-valmsg-for', newName);
if ($(this).attr('id') != undefined) {
var oldid = $(this).attr('id');
var oldidSuffix = oldid.substr(oldid.indexOf('__'));
var newIdSuffix = oldidSuffix.replace('_' + suffix + '__', '_' + index + '__');
var newId = oldid.replace(oldidSuffix, newIdSuffix);
$(this).attr('id', newId);
if (val.tagName == "INPUT" && val.type == "text") {
$(this).val(0);
}
}
$(this).removeClass("input-validation-error");
});
$TableBody.find('tr:last').after($trNew);
var form = document.getElementById("my-form");
$(form).removeData("validator") // Added by jQuery Validation
.removeData("unobtrusiveValidation"); // Added by jQuery Unobtrusive Validation
$.validator.unobtrusive.parse(form);
});
});
});
</script>
}
Controlloer
public IActionResult Index()
{
Material material = new Material();
material.BidGroupsList = new List<BidGroups>();
material.BidGroupsList.Add(new BidGroups()
{
AuctionMaterials = new List<AuctionMaterial>() { new AuctionMaterial { Container = "container1" } },
BidSubmissionList = new List<BidSubmission>() { new BidSubmission { BidPrice = 111 } }
});
return View(material);
}
public IActionResult AuctionMaterials(Material model)
{
return null;
}
public class Material
{
public List<BidGroups> BidGroupsList { get; set; }
}
public class BidGroups {
public List<AuctionMaterial> AuctionMaterials { get; set; }
public List<BidSubmission> BidSubmissionList { get; set; }
}
public class BidSubmission {
[Required]
[Range(10,1000,ErrorMessage = "BidPrice must between 10 to 1000")]
public int BidPrice { get; set; }
}
public class AuctionMaterial {
public string Container { get; set; }
}
Result:
For more details, you could refer to this document:
ASP.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today. Learn more >
Member
1 Points
3 Posts
dynamically add validation in validationmessagefor a table using jquery asp.net mvc
Feb 01, 2021 10:59 AM|A DJ|LINK
Hi Friends,
am working on project where i need to enable the users to add and delete rows to a table dynamically and validate its data, I have followed the same logic which was implemented on this post https://forums.asp.net/t/2172919.aspx?dynamically+add+validation+in+validationmessagefor+a+table+using+jquery+asp+net+mvc
The solution is working as expected for adding a record but the validation doesnt work for the new add input controls any advise on this regard
Contributor
2350 Points
743 Posts
Re: dynamically add validation in validationmessagefor a table using jquery asp.net mvc
Feb 02, 2021 05:53 AM|XuDong Peng|LINK
Hi A DJ,
According to your description, I create a simple demo to reproduce your issue and test these code.
I think the cause of this issue is here:
var LastIndexForSuffix = $trNew.find(':input:first').attr('name').lastIndexOf('[');
In browser console, will it display such an error message? --> Cannot read property 'lastIndexOf' of undefined
You can see that it has an operation to get the name attribute, but in the page element, the input does not contain the name attribute.
Something like this (in page element):
You need to create a verification code template for script cloning. In Page code:
<div> <table class="table"> <thead> <tr> <th class="cell "> @Html.DisplayNameFor(model => model.BidGroupsList[0].BidSubmissionList[0].BidPrice) </th> </tr> </thead> <tbody> @for (int BidSubmissionIndex = 0; BidSubmissionIndex < Model.BidGroupsList[CategoryIndex].BidSubmissionList.Count(); BidSubmissionIndex++) { <tr> <td> @*<input asp-for="@Model.BidGroupsList[CategoryIndex].BidSubmissionList[BidSubmissionIndex].BidPrice" class="form-control" />*@ @*<span asp-validation-for="@Model.BidGroupsList[CategoryIndex].BidSubmissionList[BidSubmissionIndex].BidPrice" class="text-danger"></span>*@ @Html.EditorFor(model => model.BidGroupsList[CategoryIndex].BidSubmissionList[BidSubmissionIndex].BidPrice) @Html.ValidationMessageFor(model => model.BidGroupsList[CategoryIndex].BidSubmissionList[BidSubmissionIndex].BidPrice) </td> </tr> } </tbody> </table> <input type="button" id="add" class="btn btn-primary AddButton" value="Add" /> </div>
If I misunderstood anything, could you provide more details, mainly including : relevant sample code, how to test the code and the problems encountered.
Best regards,
Xudong Peng
Member
1 Points
3 Posts
Re: dynamically add validation in validationmessagefor a table using jquery asp.net mvc
Feb 02, 2021 06:31 AM|A DJ|LINK
Thank you very much for your reply, in my case my model has a master "BidGroupList" and child "BidSubmissionList" array, for that am using the below script to change the second index in the array
in your test sample it has a single object for that it will not work as there is no array or object index,
Thank you very much for your help
Contributor
2350 Points
743 Posts
Re: dynamically add validation in validationmessagefor a table using jquery asp.net mvc
Feb 03, 2021 09:39 AM|XuDong Peng|LINK
Hi A DJ,
I think I may have misunderstood what you mean. I recreated an example to test your code, and modified some of the code to fix the problem.
public class Material { public List<BidGroups> BidGroupsList { get; set; } } public class BidGroups { public List<AuctionMaterial> AuctionMaterials { get; set; } public List<BidSubmission> BidSubmissionList { get; set; } } public class BidSubmission { [Required] [Range(10,1000,ErrorMessage = "BidPrice must between 10 to 1000")] public int BidPrice { get; set; } } public class AuctionMaterial { public string Container { get; set; } }
Result:
For more details, you could refer to this document:
https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-5.0#add-validation-to-dynamic-controls
Best regards,
Xudong Peng
Member
1 Points
3 Posts
Re: dynamically add validation in validationmessagefor a table using jquery asp.net mvc
Feb 03, 2021 10:04 AM|A DJ|LINK