In my MVC 5 application I have multiple tables based on a grouping. In the tables it is possible to change some values. When the FirstName field is empty. When I submit the form, client-side validation is not working and I don't know why.
Model:
public class ResourceModel
{
public int Id { get; set; }
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
Controller:
public ActionResult Employee()
{
List<ResourceModel> resources = new List<ResourceModel>();
resources.Add(new ResourceModel() { Id = 1, FirstName = "Piet", LastName = "Willemse" });
resources.Add(new ResourceModel() { Id = 2, FirstName = "Jan", LastName = "Janssen" });
resources.Add(new ResourceModel() { Id = 3, FirstName = "Willem", LastName = "Willemse" });
resources.Add(new ResourceModel() { Id = 4, FirstName = "Hendrik", LastName = "Willemse" });
resources.Add(new ResourceModel() { Id = 5, FirstName = "James", LastName = "Janssen" });
return View(resources.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Validation(List<ResourceModel> resource)
{
if(ModelState.IsValid != true)
{
return RedirectToAction("Employee");
}
return RedirectToAction("Employee");
}
View:
@model List<EmployeeApp.Models.ResourceModel>
@{
ViewBag.Title = "Employee";
}
<h2>Employee</h2>
@using (Html.BeginForm("Validation", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
int i = 0;
foreach (var grp in Model
.OrderBy(m => m.LastName)
.GroupBy(m => new { m.LastName }))
{
<table>
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
@foreach (var itm in grp)
{
<tr>
<td>
<input type="hidden" value="@i" name="Index" />
@Html.TextBoxFor(m => itm.FirstName, new { Name = "[" + i + "].FirstName", @id = "[" + i + "].FirstName" })
</td>
<td>
@Html.TextBox("[" + i + "].LastName", itm.LastName)
@Html.ValidationMessage("[" + i + "].LastName")
</td>
</tr>
i++;
}
</tbody>
</table>
}
<input type="submit" value="submit" />
}
When I change my view to:
<table>
<thead><tr><td>First name</td><td>Last name</td></tr><thead>
<tbody>
for(int i = 0; i < Model.Count(); i++)
{
<tr>
<td>@Html.TextBoxFor(m => m[i].FirstName)</td>
<td>@Html.TextBoxFor(m => m[i].LastName)
@Html.ValidationMessageFor(m => m[i].LastName)</td>
</tr>
}
</tbody>
</table>
Client-side validation is working.
@grp.Key.LastName
` – kwv84 Dec 01 '15 at 11:28