Search code examples
c#ajaxasp.net-coreasp.net-core-mvcasp.net-validators

Show the validation error from the AJAX calls inline on the field


I am trying to show the error message on the field (inline) when the validation fails returned from the AJAX call.

        <input type="text" class="text-danger float-right" style="border:none;font-size: smaller" id="@("errorMessage")" readonly />
        <div class="form-group">
            <label asp-for="OrderQuantity" class="control-label"></label>
            <input asp-for="OrderQuantity" id="txt" class="form-control" />
            <span asp-validation-for="OrderQuantity" class="text-danger"></span>
        </div>
        <input type="hidden" id="orderId" name="orderId" value="@Model.OrderId" />
        <button id="button">Click Me</button>
    </form>
 </div>
</div>

@section Scripts {
 <script type="text/javascript">
$("#button").click(function () {
    var orderedQuantity = $("#txt").val();
    var orderId = $("#orderId").val();
    var data = {
        orderId: orderId,
        orderedQuantity: orderedQuantity
    };

    $.ajax({
        type: 'POST',
        url: '@Url.Action("EditItem", "Orders")',
        data: data,
        dataType: "json",
        success: function (result) {
            if (result.status === "NotAvailable") {
                alert("NotAvailable");
                $("#errorMessage").val("Enter a valid Quantity");
            }
            else {
                var url = '@Url.Action("Index", "Orders")';
                window.location.href = url + "[email protected]";
            }
        },
        error: function (error) {
                alert(error);
            }
    });
});
</script>

}

The form and the AJAX call is like below

When the result.status returned from the controller action is "NotAvailable" I am creating error message like $("#errorMessage").val("Enter a valid Quantity"); and using this at the top of my field

        <input type="text" class="text-danger float-right" style="border:none;font-size: smaller" id="@("errorMessage")" readonly />

When try to test the validation failure scenario after I click on the button below is what I am seeing

enter image description here

How can I comeback to the same screen and show the error Enter a valid Quantity on the field


Solution

  • You need following modifications:

    Set your button type like this : <button id="button" type="button">Update</button> instead of <button id="button">Click Me</button>

    Note: By defualt button type is submit so it always post additional form POST Request so that you are redirecting to that page.

    Output:

    enter image description here

    Update: Though I think your errorMessage tag seems alright but I usually use javascript or Jquery tag slide differently as below are the full code for your reference. Feel free to customize as per your requirement.

    HTML:

        <div>
            <input type="text" class="text-danger float-right" style="border:none;font-size: smaller" id="errorMessage" readonly />
            <form asp-action="EditItem">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <div class="form-group">
                    <label asp-for="OrderQuantity" class="control-label"></label>
                    <input asp-for="OrderQuantity" id="txt" class="form-control" />
                    <span asp-validation-for="OrderQuantity" class="text-danger"></span>
                </div>
                <input type="hidden" id="orderId" name="orderId" value="123456" />
                <input type="hidden" id="inventoryorderId" name="inventoryorderId" value="22222" />
                <input type="hidden" id="inventoryId" name="inventoryId" value="3333" />
                <button id="button" type="button">Update</button>
            </form>
        </div>
    

    Javascript:

    @section Scripts {
        <script type="text/javascript">
        $("#button").click(function () {
            var orderedQuantity = $("#txt").val();
            var orderId = $("#orderId").val();
            var inventoryorderId = $("#inventoryorderId").val();
            var inventoryId = $("#inventoryId").val();
            var data = {
                orderId: orderId,
                inventoryorderId: inventoryorderId,
                inventoryId: inventoryId,
                orderedQuantity: orderedQuantity,
            };
    
            $.ajax({
                type: 'POST',
                url: '@Url.Action("EditItem", "Order")',
                data: data,
                dataType: "json",
                success: function (data) {
                    console.log(data);
    
                    if (data.status === "NotAvailable") {
                        alert("NotAvailable");
                        $("#errorMessage").val("Enter a valid Quantity");
                        return false;
                    }
                    else {
                        alert("Else fired");
                          var url = '@Url.Action("Index", "Order")';
                    window.location.href = url;
                    }
    
                },
                error: function (error) {
                    alert("Alert");
                }
            });
        });
        </script>
    }
    

    Hope that would resolve your problem.