0

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:-

View looks like this What am I missing?

Ram
  • 527
  • 1
  • 10
  • 26
  • Have you set this ".validation-summary-valid { display:none; }" ??? – Naman Upadhyay Feb 18 '19 at 09:22
  • @NamanUpadhyay - see edited Code - still same error... – Ram Feb 18 '19 at 09:33
  • Okay you have different class name in your code so try with this "validation-summary-valid text-danger { display:none; }" – Naman Upadhyay Feb 18 '19 at 09:37
  • @NamanUpadhyay - tried with your suggestion, same result - still doesn't work – Ram Feb 18 '19 at 09:41
  • 1
    put @Html.ValidationSummary("", new { @class = "validation-summary-valid text-danger" }) inside form tag – Azhar Feb 18 '19 at 09:51
  • @Azhar - done that - problem still persists... – Ram Feb 18 '19 at 10:01
  • @MaiurLaximidas Is there any referenced JS file on this view? If yes, can you confirm if there is any script validating the form on page load? – Yom T. Feb 18 '19 at 10:01
  • @jom - edited View to show Scripts validation – Ram Feb 18 '19 at 10:04
  • @MaiurLaximidas [This post](/a/5874405/3634538) seems to suggest the same workaround as mentioned by @NamanUpadhyay. Maybe try forcing the style, like: `display: none !important`. – Yom T. Feb 18 '19 at 10:07
  • This is strange. as @jom said, it's like something else is triggering the unobtrusive validation on your page load. Is there any 'document ready' or 'window load' JS being executed anywhere else in the `_Layout` perhaps? Or, do you have any other forms (e.g. a nav search) on the page that could be causing it. **I would find the cause rather than patching by hiding the validation errors** – scgough Feb 18 '19 at 10:07
  • @scgough = I agree completely finding the root cause is what I want to do but am not having much luck - it seems when the page loads somehow it seems to think a page submission has taken place - if I clear the modelstate (commented out in my code) when I click add the ValidationSummary isn't displayed. I am not sure where else to look.... – Ram Feb 18 '19 at 10:41
  • try this .validation-summary-errors ul { list-style: none; margin-left:-40px } – Azhar Feb 18 '19 at 10:43
  • have you checked Chrome's dev tools (specifically the 'Network' tab) to see if any POST actions happen inadvertently? Alternatively, put a breakpoint on every possible POST controller action and see if any catch on your page load? – scgough Feb 18 '19 at 10:51

1 Answers1

1

You want this validation text to only appear when data has been sent - so it would work for your scenario to only show it when the current method of the HTTP request is not a "GET" request:

@if (Request.HttpMethod != "GET") {
    Html.ValidationSummary("", new { @class = "validation-summary-valid text-danger" });
}

This one is coming from experience (don't take it as infallible fact), but as much as possible it's better to not render something at all when you know you don't need to, rather than rendering it and then hiding it with CSS (what if you reuse the code? class changes? why expose validation info to someone who hasn't done a POST?)

Ken
  • 89
  • 1
  • 8