0

Test.cshtml:

function insertButton(item) {
        var options = {};
        options.url = "/api/test";
        options.type = "POST";
        var obj = datas;
        obj.name = $("#insertName").val();
        obj.url = $("#insertUrl").val();
        console.dir(obj);
        options.data = JSON.stringify(obj);
        options.contentType = "application/json";
        options.dataType = "html";

        options.success = function (msg) {
            swal({ type: "success", title: msg, showConfirmButton: !1, timer: 2000 })
            getAll();
        },
        options.error = function (msg) {
            swal({ title: "ERROR", text: msg, icon: "error", type: "error", confirmButtonText: "OK" })
        };

        $.ajax(options);
    }

TestController.cs

    [HttpPost]
    [Route("api/test")]
    public async Task<IActionResult> InsertData([FromBody]Sites sites)
    {
        _context.Add(sites);
        await _context.SaveChangesAsync();
        return new ObjectResult($"{sites.Name} added");
    }

How can I return a message to Ajax "options.error"? And Name + Url are "[Required]" in Model, but empty fields are still saved...

1 Answer 1

0

Well, you're not checking if the model is valid or not:

if (!ModelState.IsValid)
    return new BadRequest(ModelState);

Add that at the start of your action and you're good to go.

Alternatively, if you're using ASP.NET Core 2.1+, you can simply add the [ApiController] attribute to your controller class. Then this check will happen for you automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.