简体   繁体   中英

Cancel action and show alert from MVC controller


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.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM