milosev.com
  • Home
    • List all categories
    • Sitemap
  • Downloads
    • WebSphere
    • Hitachi902
    • Hospital
    • Kryptonite
    • OCR
    • APK
  • About me
    • Gallery
    • Curriculum vitae
      • Resume
      • Lebenslauf
    • Social networks
      • Facebook
      • Twitter
      • LinkedIn
      • Xing
      • GitHub
      • Google Maps
      • Sports tracker
    • Adventures planning
  1. You are here:  
  2. Home
  3. ASP.NET

jQuery JSON error handling

Details
Written by: Stanko Milosev
Category: Core
Published: 05 July 2020
Last Updated: 09 November 2021
Hits: 1000
Here I gave one example of jQuery Ajax POST method, but problem with that example is that you don't know if returned JSON is wrong. Now I will give example when .NET side returns wrong JSON, and error handling in jQuery.

index.html remains same:

<!DOCTYPE html>
<head>
	<meta charset="utf-8" />
	<script defer type="text/javascript" src="lib/jquery-3.5.1.js"></script>
	<script defer type="text/javascript" src="js/index.js"></script>
</head>

<body>
	<button id="button" type="button">Click Me!</button>
</body>
index.js:
$( "#button" ).click(function() {
    var json = JSON.stringify({"cities": ["Aurel Vlaicu", "Asquins", "Arnoldstein"]});

    $.ajax({
        url: "api/Empty/",
        type: "POST",
        data: json,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            alert("Success.");
        }
    }).done(function (data) {
        try {
            json = $.parseJSON( JSON.stringify(data));
        } catch (e) {
            alert("Error not JSON. " + e.message)
        }
    }).error(function (xhr, ajaxOptions, thrownError) {
        alert("Error.");
    }).fail(function (data) {
        alert("Sorry. Server unavailable. ");
    }); 
});
.NET side:
    [HttpPost]
    public ActionResult Get([FromBody] Filter filter)
    {
      string returnValue = string.Empty;

      foreach (var city in filter.cities)
      {
        returnValue = $"{city}, {returnValue}";
      }

      return Ok(JsonSerializer.Serialize(returnValue));
    }
Notice that in "$.ajax.done" I added try..catch block, and JSON.stringify because of dataType: "json" jQuery will automatically parse string into JSON.

jQuery "POST" method

Details
Written by: Stanko Milosev
Category: Core
Published: 28 June 2020
Last Updated: 14 November 2021
Hits: 1165
  • core
  • javascript
Here I have explained how to create empty Asp.Net Core application, now using this article here is one example on how to use jQuery Ajax call to send JSON to Asp.Net core API.

index.html:

<!DOCTYPE html>
<head>
	<meta charset="utf-8" />
	<script defer type="text/javascript" src="lib/jquery-3.5.1.js"></script>
	<script defer type="text/javascript" src="js/index.js"></script>
</head>

<html xmlns="http://www.w3.org/1999/xhtml">
	 <button id="button" type="button">Click Me!</button> 
</html>
index.js:
$( "#button" ).click(function() {
    var json = JSON.stringify({"cities": ["Aurel Vlaicu", "Asquins", "Arnoldstein"]});

    $.ajax({
        url: "api/Empty/",
        type: "POST",
        data: json,
        contentType: "application/json; charset=utf-8"
    }).done(function (data) {
        alert("Success.");
    }).fail(function (data) {
        alert("Sorry. Server unavailable. ");
    }); 
});
Asp.Net core API:
using Microsoft.AspNetCore.Mvc;

namespace AspDotNetCorePostExample.Controllers
{
  [Route("api/[controller]")]
  [ApiController]
  public class EmptyController : ControllerBase
  {
    [HttpGet]
    public string Get()
    {
      return "Hello world";
    }

    [HttpPost]
    public string Get([FromBody] Filter filter)
    {
      string returnValue = string.Empty;

      foreach (var city in filter.cities)
      {
        returnValue = $"{city}, {returnValue}";
      }

      return returnValue;
    }

    public class Filter
    {
      public string[] cities { get; set; }
    }

  }
}
Notice in jQuery that in Ajax call I didn't add dataType: "json" since my API returns string and not JSON. In API notice [FromBody] in method signature, and Filter class which is defined exactly the same as JSON var json = JSON.stringify({"cities": ["Aurel Vlaicu", "Asquins", "Arnoldstein"]}); which I am sending to API.

Example download from here

Start empty Asp.Net core project

Details
Written by: Stanko Milosev
Category: Core
Published: 27 June 2020
Last Updated: 05 April 2022
Hits: 1142
  • core
One my example how to start empty Asp.Net core project in Visual Studio 2019, and add one controller to it.

Start empty Asp.Net core project:

Choose ASP.NET Core Web Application:

Choose "Empty":

Since I am not using reSharper, I had to create "Controllers" folder manually. Open some file from solution and right click on tab and open containing folder:

Create new folder and name it "Controllers":

Your folder structure now should look like:

In "Controllers" folder in create new file, and Name it like EmptyController.cs, write something like

using Microsoft.AspNetCore.Mvc;

namespace AspDotNetCorePostExample.Controllers
{
  [Route("api/[controller]")]
  [ApiController]
  public class EmptyController : ControllerBase
  {
    [HttpGet]
    public string Get()
    {
      return "Hello world";
    }
  }
}
In AspDotNetCorePostExample\AspDotNetCorePostExample\Startup.cs in method "Configure" delete:
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
	  {
	await context.Response.WriteAsync("Hello World!");
  });
});
Instead write:
app.UseEndpoints(endpoints =>
{
	endpoints.MapControllers();
});
In ConfigureServices add services.AddControllers();

Start solution and go to like "https://localhost:44336/api/Empty" (just add /api/Empty)

If you like you can manually add wwwroot folder, and use him like I already explained here. Here is new Startup.cs, and to disable HTPPS go to project properties -> Debug -> uncheck "Enable SSL":

wwwroot

Details
Written by: Stanko Milosev
Category: Core
Published: 01 February 2020
Last Updated: 09 November 2021
Hits: 1323
In order to serve static files in Asp.Net Core you will need following line in Startup.cs method configure:
app.UseStaticFiles();
When deploying in order to show default document, add following line:
app.UseDefaultFiles();
My whole Startup.cs looks like this:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace AllPics2gMaps
{
  public class Startup
  {
    public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }
      else
      {
        app.UseHsts();
      }

      app.UseHttpsRedirection();
      app.UseMvc();
      app.UseDefaultFiles();
      app.UseStaticFiles();
    }
  }
}
UPDATE; Please note thatStartup.cs has been changed, refer to this article.
  1. Enable Cross-Origin Requests (CORS) in ASP.NET Core
  2. Debug Asp.Net core on IIS by attaching to process
  3. Debug Asp.Net core on IIS in VS2017
  4. Publish Asp.Net core to IIS

Subcategories

MVC 4

MVC 3

WebApi

Core

Page 10 of 11

  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11