Different ways of doing serialization and deserialization in .Net (Asp.net/Asp.net MVC) (Part 3)


Method1

Method 1: Using System.Runtime.Serialization.Json Namespace

Method 2: Using System.Web.Script.Serialization Namespace

Method 3:

In this method we will use the Newtonsoft.Json dll

This is one of the most popular open source dll, we install it from Nuget package manager or from google download it and add to our project

We can write code as given below


using Newtonsoft.Json;
using System;

namespace WebApplication1
{
    public partial class Demo3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            EmpDemo objEmp = new EmpDemo
            {
                Id = 1021,
                EmpName = "Chandradev",
                EmpAddress = "Bangalore"
            };

            string jsonData = JsonConvert.SerializeObject(objEmp);
            Response.Write("<b>Converting to Json </b> " + "</br>");
            Response.Write("</br>");
            Response.Write(jsonData);
            Response.Write("</br>");

            var objEmp1 = JsonConvert.DeserializeObject<EmpDemo>(jsonData);
            Response.Write("</br>");
            Response.Write("Converting Json to .Net Object:");
            Response.Write("</br>");
            Response.Write("Id: " + objEmp1.Id + "</br>");
            Response.Write("EmpName: " + objEmp1.EmpName + "</br>");
            Response.Write("EmpAddress: " + objEmp1.EmpAddress + "</br>");
        }

        public class EmpDemo
        {
            public int Id { get; set; }
            public string EmpName { get; set; }
            public string EmpAddress { get; set; }
        }
    }
}

Note: donot forget to include the Newtonsoft.Json namespace in your code. This approach can be used in Asp.net or asp.net mvc application.

Advertisement

Different ways of doing serialization and deserialization in .Net (Asp.net/Asp.net MVC)(Part 2)


different-ways-of-doing-serialization-and-deserialization-in-net-asp-netasp-net-mvc (Part 1)

Method 2 approach

we will use System.Web.Script.Serialization namespace of .net framework

Step 1: Create the EmpDemo Class and write the code in code behind file like given below


using System;
using System.Web.Script.Serialization;

namespace WebApplication1
{
    public partial class Demo1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            EmpDemo objEmp = new EmpDemo
            {
                Id = 1021,
                EmpName = "Chandradev",
                EmpAddress = "Bangalore"
            };

            JavaScriptSerializer js = new JavaScriptSerializer();

            Response.Write("<b>Converting to Json </b> " + "</br>");
            Response.Write("</br>");
            string jsonData = js.Serialize(objEmp);
            Response.Write(jsonData);
            Response.Write("</br>");

            var objEmp1 = js.Deserialize(jsonData);
            Response.Write("</br>");
            Response.Write("<b> Converting Json to .Net Object: </b>");
            Response.Write("</br>");
            Response.Write("Id: " + objEmp1.Id + "</br>");
            Response.Write("EmpName: " + objEmp1.EmpName + "</br>");
            Response.Write("EmpAddress: " + objEmp1.EmpAddress + "</br>");
        }
    }

    public class EmpDemo
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
    }
}

Summary: This approach will be suitable in asp.net or asp.net mvc application.

Jquery Ajax in Asp.net MVC (Part 16)


In this post i will show you how to use Jquery Ajax method in Asp.net MVC. This topic is very vast but I will create very simple example to test this method in asp.net MVC.

calling_jquey_ajax

Step 1: Create one blank asp.net MVC application. I hope you are knowing the basic concept of asp.net MVC.

Step 2: Create Emp Class in Model folder and write the code like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AjaxDemoInMVC.Models
{
    public class Emp
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
    }
}

Step 3: Create the HomeController and the DisplayEmpDetail Method like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AjaxDemoInMVC.Models;

namespace AjaxDemoInMVC.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult DisplayEmpDetail(int id)
        {
            Emp obj = new Emp
            {
                 Id=id,
                 EmpName="Chandradev",
                 EmpAddress="Bangalore"
            };
            return Json(obj);
        }
    }
}

Note: Here we are returning the values as Json format.

Step 4: Create the Index view and Write the code for calling the method using Jquery Ajax method as given below


@model AjaxDemoInMVC.Models.Emp

@{
    ViewBag.Title = "Index";
}

<fieldset>
    <legend>
        Sample code for Calling Jquery Ajax in asp.net MVC
    </legend>

    <br />

EmpId: <input type="text" id="txtId" />
<input type="button" id="btnAjax"  value="Click Here to Call Jquery Ajax" />
</fieldset>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script>
    $(function () {
        $("#btnAjax").click(function () {
            $.ajax({
                type: "POST",
                url: "Home/DisplayEmpDetail",
                data: '{Id: "' + $("#txtId").val() + '" }',
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    alert("EmpName: "+ response.EmpName + "   EmpAddress: " + response.EmpAddress);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }

            });

        });

    });
</script>

Note : In the above code we show that we are using jquery Ajax method on button Click event and Ajax method expect the type, URL,Data,ContentType,Success,Failure and error parameter.

Type: means Type of Request in Ajax method

URL: Means Method name which are using for Ajax functionality.

data: what are the input data being used in method

ContentType: What are the content type consuming in Ajax method. We are giving data in Json format in DisplayEmpDetail Method.

success: What will return the method on successfully execution.

failure: It will define what message should be display on failure of Ajax method
error: It will display the error message.

Summary: We show that how to use Jquery Ajax method in asp.net MVC application.

How to display the warning message in asp.net mvc ?


Warning_Msg

while working in asp.net mvc we will get scenario to display the alert or warning message while deleting or editing the record, then we can achieve that functionality by using this code as given below


// Alert message for edit record
@Html.ActionLink("Edit","Index",new {Id=item.Id},new { onclick = "return confirm('Are you sure do you want to edit the record ?');" })
// Alert message for delete the record.
@Html.ActionLink("Delete","Delete",new {Id=item.Id},new { onclick = "return confirm('Are you sure you wish to delete this record "+@item.Id +"?');" })