简体   繁体   中英

How do I access the returned json data from my controller from my ASP.NET Core AJAX form?

In my ASP.NET Core 3.1 web application, I have created a very basic Ajax form that makes use of the Unobtrusive Ajax library. When the form us submitted a check is carried out to find if a record with the same name currently exists and if it does, return any records that match that name as a Json Result along with the outcome of the request.

<form asp-controller="Test" asp-action="Create" id="CreateForm"
    data-ajax="true"
    data-ajax-method="POST">

    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <div class="md-form form-group">
        <label asp-for="Name"></label>
        <input type="text" asp-for="Name" />
    </div>
    <div class="md-form form-group">
        <button type="submit" value="Save" class="btn btn-info">Save</button>
    </div>
</form>

Here is the controller that handles this form when it's submitted.

[HttpPost]
public IActionResult Create(Test model)
{            
    if (ModelState.IsValid)
    {
        bool safetyCheck = _testService.GetTests().Any(x => x.Name == model.Name);

        if (safetyCheck == true)
        {
            var something = _testService.GetTests()
                .Where(x => x.Name == model.Name /*&& x.Active == model.Active*/)
                .Select(x => new { x.Id, x.Name })
                .ToList();

            return Json(new { success = false, error = something });
        }
        else {
            //Add Record
            _testService.InsertTest(model);
            return Json(new { success = true });
        }
    }
    else {
        return View();
    }
}

As you can see, the model is passed in, the model state is checked for validity and then a check is carried out to find out if the name passed in from the model matches any currently existing record. If the check is true then I create an object that can be sent back to the view via JSON along with the success = false .

If the name doesn't exist then the record is simply created.

What I want to know is, once this JSON data is returned, how do I then use it in my view, for example. If I return a list of all the records with the same name as I do above, how would I show the user this information along with a message?

In short, you'd need to write a custom JS function to process the return data. To hook it up to the AJAX request completion you can specify it in data-ajax-complete attribute value on your form.

It will look approximately like this:

<form asp-controller="Test" asp-action="Create" id="CreateForm"
    data-ajax="true"
    data-ajax-method="POST"
    data-ajax-complete="ajax_handler">

    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <div class="md-form form-group">
        <label asp-for="Name"></label>
        <input type="text" asp-for="Name" />
    </div>
    <div class="md-form form-group">
        <button type="submit" value="Save" class="btn btn-info">Save</button>
    </div>
</form>

@section Scripts
{
    ...
    <script>
        ajax_handler = function (xhr) {
            var data = xhr.responseJSON;
            // Process returned data here
        };
    </script>
}

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