Home > Software engineering >  Cancel action and show alert from MVC controller
Cancel action and show alert from MVC controller

Time:12-21


I am trying to validate the content of an excel file in a mvc controller. I have some simple html input with a javascript script that retrieves the content of the file in JSON format. I then proceed to call an action that has to validate the JSON. If it is valid it should redirect to the home page. If not valid it should cancel the action and display an alert containing feedback. Here is the action:

public IActionResult Upload()
{
    string json = Request.Form["xlx_json"].ToString(); //Text area containing json

    try
    {
        List<WarehouseOrderModel> orders = JsonConvert.DeserializeObject<List<WarehouseOrderModel>>(json, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            DefaultValueHandling = DefaultValueHandling.Ignore
        });

        string validation_results = RequestBodyValidator.Validate(orders);

        if (string.IsNullOrEmpty(validation_results))
            return RedirectToAction("Index", "WarehouseOrders");
        else
            // invalid in this case
    } catch
    {
        // invalid in this case
    }
}

I have already tried everything from this question, I just can't seem to make it work. I would appreciate your help. Thanks in advance.

CodePudding user response:

You can Use Ajax and in controller use Ok and BadRequest result for your validation then you can check in Ajax if error happend show alert and if successed redirect it to where you want. in client:

$.ajax({
        url: url,
        data: $('input[name="xlx_json"]').val(),
        cache: false,
        success: function (result) {
                window.location.href = "your url";
        },
        error: function (xhr, status, error) {
            // Display a generic error for now.
            //alert("AJAX Error!");
        }
    });

in backend:

public IActionResult Upload()
{
    string json = Request.Form["xlx_json"].ToString(); //Text area containing json

    try
    {
        List<WarehouseOrderModel> orders = JsonConvert.DeserializeObject<List<WarehouseOrderModel>>(json, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            DefaultValueHandling = DefaultValueHandling.Ignore
        });

        string validation_results = RequestBodyValidator.Validate(orders);

        if (string.IsNullOrEmpty(validation_results))
            return OK();
        else
            return BadRequest();
    } catch
    {
            return BadRequest();
    }
}
  • Related