2

I have a Razor Pages page with some JavaScript sending form data to an API. The API tries to update the database, if there is a concurrency conflict, it returns 409. The JavaScript then checks if the response status is 409 and accordingly alerts the user with a message such as Conflict detected. Q: How do I send back context along with the Response so that the user can see which data has triggered the Conflict?

JavaScript:

var response = await fetch("api/dsr/updateStatus", {
                    method: "POST",
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

               if (response.status == 409) {
                    alert("Conflict detected.");
                }

Controller code

IEnumerable<DSR> changedDsrs = // DetectIfConflict();

if (changedDsrs.Any())
{
    return Conflict();
}

I have tried changing the last line to return Conflict(new { statusText = changedDsrs.First().ReleaseId.ToString()}); to no avail. The posted code works fine: if there is indeed a conflict detected than the 409 is returned and the user is alerted - I just want to know how to add context to the alert text to display info from the changedDsrs

Zvi
  • 65
  • 5
  • Have a look at this - might answer your question: https://stackoverflow.com/a/43335622/660223 – Winks Jul 05 '22 at 19:34

1 Answers1

1

Controller:

You can return the following:

if (changedDsrs.Any())
            {
                return Conflict(new { message = $"An existing dsr was found." });
            }

And in JavaScript:

var response = await fetch("api/dsr/updateStatus", {....

response that fetch returned is a JavaScript promise. You can use await on it again to see the properties available.

For example

var text = await response.text();

See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

Winks
  • 580
  • 1
  • 7
  • 17
  • no need to send an object inside Conflict, I can send a plain string e.g. `return Conflict("An existing dsr was found.")`. Thank you for your direction. – Zvi Jul 06 '22 at 07:44
  • any idea why i cant seem to actually get the message text on the client via JS? its always just null or some BS status text "The page was not displayed because there was a conflict." I can never seem to find my custom text – d0rf47 Aug 10 '22 at 17:38
  • @d0rf47 that was my problem - the answer is you need to write `var text = await response.text();`, i.e. you need to await the response – Zvi Sep 02 '22 at 08:51
  • @Zvi i was actually awaiting it, what the issue ended up being in my particular case was a result of our IIS configurations. It was not properly configured for custom status responses so it was always just giving the standard 4xx error msg. I was able to change it though and now it works :) – d0rf47 Sep 02 '22 at 12:59