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
- {
-
-
-
- [Serializable]
- public class BLResult
- {
- public BLResult()
- {
-
-
-
- }
- 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; }
- }
- }
-
-
-
-
- [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.