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


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.

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.

webgrid reference is not found in asp.net view


While working with Webgrid in asp.net mvc, I was not getting the reference in view. Then i fixed the issue like this,

Step 1: Firstly i added the System.web.helper dll

Step 2: I went to the property of dll and change CopyLocal to True.

webgrid

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 +"?');" })

How to make multiline text box in asp.net MVC


If you are working on asp.net mvc and you got the scenario to make Multiline text box, where user can enter the long text.

Then you can do like this

Step 1 : Take the @html.TextAreaFor html helper

Step 2: Increase the height and weight of TextArea like this

@Html.TextAreaFor(model => model.Answer,5, 55, null)

Note : Here Model.Answer is the part of my model class.

How to upload multiple files in Asp.net MVC ?


MultipleFile

There are so many ways to do this task in asp.net MVC. But this is one of the easiest ways to upload multiple file.
In this approach we are using Html 5.0 fileupload control. If the browser will not support HTML 5 then it will display in traditional ways.

Step1: Create the blank asp.net mvc application and write the UI code in index view like this


@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div id="multiple">
        <input type="file" class="multiple" name="files" multiple />
    </div>
    <div id="single">
        <input type="file" class="single" name="files" /><br />
        <input type="file" class="single" name="files" /><br />
        <input type="file" class="single" name="files" /><br />
    </div>
    <button class="btn btn-default">Upload</button>
}

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

    <script type="text/javascript">
        $(function () {
            if(window.FileReader != null){
                $('#single').hide();
                $('.single').prop('disabled', true);
            } else {
                $('#multiple').hide();
                $('.multiple').prop('disabled', true);
            }
        });
    </script>

Note: If the browser doesn’t support html 5 then this jquery script code will activate Single fileupload option.

Step 2: Write the code in Home controller for file upload like this given below



using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace MultipleFileUpload.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FileUpload(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (var file in files)
            {
                if (file != null && file.ContentLength > 0)
                {
                    file.SaveAs(Path.Combine(Server.MapPath("/Images"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
                }
            }
            return View("Index");
        }
    }
}

Summary: We show that how to upload multiple file in asp.net MVC.