This blog includes a step by step tutorial to learn ajax and get effective way response on success with the help of ASP.Net MVC.
- Create a class in project Blresult.cs
This class is generic List<T> class so you can assign any type of data and get a response in an effective way.- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace TestAPP.Helper
- {
- /// <summary>
- /// Base Class for returning result used in Pubmed Services as well Windows application
- /// </summary>
- [Serializable]
- public class BLResult
- {
- public BLResult()
- {
- //
- // TODO: Add constructor logic here
- //
- }
- private string _ResultMessage = string.Empty;
- private bool _Success = false;
- public bool Success
- {
- get { return _Success; }
- set { _Success = value; }
- }
- public string ResultMessage
- {
- get { return _ResultMessage; }
- set { _ResultMessage = value; }
- }
- }
- /// <summary>
- /// Generic class for returning result used in Pubmed Services as well Windows application
- /// </summary>
- /// <typeparam name="T"></typeparam>
- [Serializable]
- public class BLResult<T> : BLResult
- {
- protected T _GenericValue = default(T);
- public BLResult()
- { }
- public T Value
- {
- get { return _GenericValue; }
- set { _GenericValue = value; }
- }
- }
- }
- Create method on HomeController.cs
Currently, I have declared integer value in Blresult. We can also use a class instead of integer value, but type of data added in Blresult you must set that type of data in response.- public JsonResult GetTestData(int Id) {
- try {
- BLResult < int > blresult = new BLResult < int > ();
- if (Id != 0) {
- blresult.Success = true;
- blresult.ResultMessage = "Data get successfully";
- blresult.Value = 25;
- } else {
- blresult.Success = false;
- blresult.ResultMessage = "Data is not found";
- blresult.Value = 0;
- }
- return Json(blresult, JsonRequestBehavior.AllowGet);
- } catch (Exception ex) {
- throw;
- }
- }
- Call action method using ajax and handle response in ajax success.
This ajax example is given result in success and we can handle easily. So we can manage data easily on success response.- $.ajax({
- type: "GET",
- url: "/Vendor/GetTestData/2",
- contentType: "application/json; charset=utf-8",
- success: function (result) {
- if (result.Success) {
- $("#txtTest").val(result.Value)
- alert(result.ResultMessage);
- }
- else {
- console.log(result.ResultMessage)
- }
- },
- error: function (error) {
- console.log(error);
- }
- });
Thank you and happy coding.

Aakash MauryaPosted Aug 13, 2019, 2:18 AM
Great Start..
Libo HuPosted Aug 12, 2019, 2:17 AM
Good share
Garry SmithPosted Aug 11, 2019, 5:35 PM
Hello Everyone i am new here