Full-Stack freelance Umbraco developer in the UK.

George Phillipson - Freelance Umbraco developer

Return The Response From An Asynchronous Call

Return The Response From An Asynchronous Call
$(document).ready(function () {
    $("#param").on("change", function (e) {
        e.preventDefault();
        $("#ajaxFindDetails").hide();
        $("#ajaxFindDetails").html("");
        jQuery.ajax({
            url: "/AsyncExample/Result",
            type: "POST",
            data: { 'param': $("#param").val() },

            success: function (result) {
                if (result.Confirm) {
                    $("#ajaxFindDetails").append(result.message).show();
                } else {
                    $("#ajaxFindDetails").append(result.message).show();
                }
            },
            error: function () {
                $("#ajaxFindDetails").html("Failed to find details");
            }
        });
    });
});
using System;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Web.Model.TestSearchData;

namespace Web.UI.Controllers
{
    public class AsyncExampleController : Controller
    {
        // GET: AsyncExample
        public ActionResult Index()
        {
            return View("~/Views/AsyncExample/AsyncExample.cshtml");
        }

        [HttpPost]
        public ActionResult Result(string param)
        {
            //Before starting, we would check that param is not null!!
            var result = TestSearchData.DogList().Where(x=> string.Equals(x.PetTypeId, param, StringComparison.CurrentCultureIgnoreCase)).ToList();

            StringBuilder sb = new StringBuilder();
            
            if (result.Any())
            {
                sb.Append($"<h2 class=\"text-success\">Found {result.Count} results for {param}</h2>");
                sb.Append("<ol>");
                foreach (var pet in result)
                {
                    sb.Append($"<li>{pet.PetType}</li>");
                }

                sb.Append("</ol>");
            }
            else
            {
                sb.Append($"<h2 class=\"text-danger\">Found {result.Count} results for {param}</h2>");
            }

            string returnValue = sb.ToString();

            if (Request.IsAjaxRequest())
            {
                return Json(new { Confirm = true, message = $"{returnValue}" }, JsonRequestBehavior.AllowGet);
            }

            //Ignore this part as only doing async example
            return View("~/Views/AsyncExample/AsyncExample.cshtml");
        }
    }
}
using System.Collections.Generic;
using Web.Model.TypesOfPets;

namespace Web.Model.TestSearchData
{
    public static class TestSearchData
    {
        public static IEnumerable<TypeOfPetsViewModel> DogList()
        {
            List<TypeOfPetsViewModel> typesOfPet = new List<TypeOfPetsViewModel>
            {
                new TypeOfPetsViewModel("dog", "German Shepherd"),
                new TypeOfPetsViewModel("dog", "Husky"),
                new TypeOfPetsViewModel("cat", "Russian Blue"),
                new TypeOfPetsViewModel("fish", "Goldfish")
            };
            return typesOfPet;
        }
    }
}
namespace Web.Model.TypesOfPets
{
    public class TypeOfPetsViewModel
    {
        public TypeOfPetsViewModel(string petTypeId, string petType)
        {
            PetTypeId   = petTypeId;
            PetType     = petType;
        }

        public string PetTypeId     { get; }
        public string PetType       { get; }
    }
}
@{
    ViewBag.Title = "Async Example";
}

<h2>Async Example</h2>


<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1>Search Using jQuery Ajax Async</h1>
            <form name="frmAsync" id="frmAsync">
                <div class="form-group">
                    <input class="form-control" type="text" name="param" id="param" placeholder="Enter keyword 'dog' or 'cat' or 'fish'" />
                </div>
            </form>
            <div id="ajaxFindDetails"></div>
        </div>
    </div>
</div>

@section AsyncExample
{

    <script src="~/Scripts/CustomScripts/asyncExample.js"></script>
}

Please enter your comment.