I have a View which has a couple of required fields - however the ValidationSummary message should be triggered when the user clicks "Add" not when the page loads.
I have tried below link but these results in the ValidationSummary dissapearing altogether...
MVC Razor Validation Errors showing on page load when no data has been posted
public ActionResult Index(ParticipantViewModel p)
{
if (p.ClientName != null)
{
string[] split = p.ClientName.Split(',');
p.ClientName = split[0];
p.ClientConn = split[1];
d.Connection.ConnectionString = p.ClientConn;
var prt = d.Participants.Where(s => s.Id == p.Id).FirstOrDefault();
if (prt != null)
{
p.FirstName = prt.FirstName;
p.LastName = prt.LastName;
p.PayrollNo = prt.PayrollNo;
p.Id = prt.Id;
}
//ModelState.Clear();
return View(p);
}
else
{
return RedirectToAction("SearchParticipants");
}
}
Code in View:-
@Html.ValidationSummary("", new { @class = "validation-summary-valid text-danger" })
@using (Html.BeginForm("Add", "Participants", FormMethod.Post, new {@class = "form-horizontal", role =""}))
{
@Html.AntiForgeryToken()
<table class="table">
<tr>
<th>@Html.DisplayNameFor(model => model.FirstName)</th>
<th>@Html.DisplayNameFor(model => model.LastName)</th>
<th>@Html.DisplayNameFor(model => model.PayrollNo)</th>
<th>@Html.DisplayNameFor(model => model.TransDesc)</th>
<th>@Html.DisplayNameFor(model => model.Points)</th>
<th>@Html.DisplayNameFor(model => model.Actions)</th>
</tr>
<tr>
<td>@Html.DisplayFor(model => model.FirstName)</td>
<td>@Html.DisplayFor(model => model.LastName)</td>
<td>@Html.DisplayFor(model => model.PayrollNo)</td>
<td>@Html.TextBoxFor(model => model.TransDesc)</td>
<td>@Html.TextBoxFor(m => m.Points, new { onkeydown = "return ValidateNumber(event);"})</td>
<td>@Html.EnumDropDownListFor(model => model.Actions)</td>
</tr>
</table>
if (Model.FirstName != null)
{
<div class="form-actions no-color">
<input type="submit" value="Add" class="btn btn-primary"/>
</div>
}
}
@section Scripts {
<script type="text/javascript" language="javascript">
function ValidateNumber(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 96 || charCode > 105))
{
return false;
}
return true;
};
</script>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
}
Site.Css
.validation-summary-valid
{
display:none;
}
Sreenshot of View without the Add button being clicked:-