Announcement

Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Json Size Limit


json size limit techiners
This post will highlight a very common error that comes often when we visit a webpage/website that uses AJAX. We know that in AJAX we have anonymous functions like: success, error etc. success gets called when our ajax request gets successfully completed and it returns a response whereas error gets called when ajax encounters a problem in processing a request.

Server side ajax paging using jquery MVC4

Server Side AJAX paging using jquery in MVC4


Every developer has to code for a view that displays all the records. But what if the database consists of thousands of records? In that case displaying all the records on the view is not good. Rather some sort of paging must be provided that will give the user the ability to navigate among the records and even provide the developer to have fast web page. So, we need to fetch the records on demand and display them on the view. This will be much fast if records are fetched using AJAX. Pagenation can be done in different ways. One way is to use Html Helpers. i.e., @Html.PagedList. The other way is using AJAX. So, how AJAX is used for fast paging?

Deleting records using ajax and updating the content after deletion

This post will explain how to delete records from table and updating the content after deletion using ajax.

We will delete records based on the user's choice i.e., user will be given the option to select or deselect the record or records using check boxes.

We will take an example of deleting graphics from the clips that are already allocated to the clips in GraphicsClipsMap table.

For each graphics, check box will be displayed adjacent to it. One delete button is provided for deleting those selected graphics.

1. Write a function that will be called when the delete button is clicked.

2. Within this function write the code to check whether the checkbox is checked or not when the delete button is clicked. If there is no single check box checked and the user clicked the delete button, then display an error in alert to select atleast one checkbox for deletion.

  function DeleteGraphicsFromClip(playoutcode) {
            var checkedIds = [];
            var flag = 1;
            $('input[class=' + playoutcode + ']:checked').each(function () {
                if ($('input[class=' + playoutcode + ']:checked').length <= 0) {
                    alert($(this).attr("id"));
                    flag = 1;
                }
                else {
                    checkedIds.push($(this).attr("id"));
                    alert($(this).attr("id"));
                    flag = 0;
                }
            });

3. Now, pass the selected checkbox ids- the ids are the primary key associated with the graphics to be deleted, to the controller using ajax. These ids are stored in the array using javascript.

4. Flag is set to zero. Now we will pass the checked ids to the controller.

 if (flag == 0) {
                if (confirm('Do you really want to delete the checked graphics?')) {
                    alert('checked: ' + checkedIds);
                    /* pass this array of GraphicClipMap ids to controller's Delete Action Method
                    for deleting the mapped graphics from the clip */
                    $.ajax({
                        url: '@Url.Action("DeleteGraphicsFromClips", "GraphicsClipMap")',
                        data: JSON.stringify({ graphicsClipMapIds: checkedIds }),
                        dataType: 'json',
                        type: 'POST',
                        contentType: "application/json",
                        async: true,
                        success: function (result) {
                            if (result == "3") {
                                alert('You are not allowed to delete graphics form this clip. It is about to scheduled within 2 weeks time.');
                                return false;
                            }
                            if (result == "2") {
                                alert("Graphics already deleted.");
                                return false;
                            }
                            else if (result == "1") {
                                alert('Problem deleting graphics from clip.');
                                return false;
                            }
                            else {
                                /* successfully deleted: now get all graphics after deletion from the clips */
                                $.ajax({
                                    url: '@Url.Action("GetAllClips", "GraphicsClipMap")',
                                    data: JSON.stringify({ ScheduledProgrammeCode: $('#ddlProgramme :selected').val() }),
                                    dataType: 'json',
                                    type: 'POST',
                                    contentType: "application/json",
                                    async: true,
                                    success: function (clips) {
                                        showClipGraphics(clips);
                                        $('.label').show();
                                        $('#clipGrid').show();
                                    },
                                    Error: function () {
                                        alert("Unable to retrive clips due to unsuccessful ajax call.");
                                    }
                                })
                                alert('Graphics successfully deleted from this clip.');
                            }
                        },
                        Error: function () {
                            alert("Unable to delete graphics from clips due ajax call unsuccessfull.");
                        }
                    });
                }
                flag = 1;
            }
            else {
                alert('Please select graphics to delete from this clip.');
                flag = 1;
            }
    }     //finally delete function is closed here.


5. Now its time to delete Graphics from the Clips that are selected in the view using checkboxes.

   public JsonResult DeleteGraphicsFromClips(string[] graphicsClipMapIds)
        {
            string query = string.Empty;
            foreach (var graphicsClipMapId in graphicsClipMapIds)
            {
                int gmId = Convert.ToInt32(graphicsClipMapId);
                /* check if graphics Id exists or not in the graphics clip map, if
                 *  not then it is already deleted. If present, enter its history in 
                 *  the history table then delete it. */
                int deletegmIdexists = Convert.ToInt32(context.GraphicsClipMaps.Where(a => a.GraphicsClipMapId == gmId).Select(b => b.GraphicsId).SingleOrDefault());
                if (deletegmIdexists > 0)
                {
                    //string playoutCode = context.GraphicsClipMaps.Where(a => a.GraphicsClipMapId == gmId).Select(b => b.playoutcode).FirstOrDefault();
                    query = bizGraphicsClipMap.DeleteGraphicsFromClips(gmId);
                    //query = query.Replace("0",playoutCode);
                    //GetScheduledGraphics(playoutCode);
                }
                else
                {
                    //Already deleted.
                    query = "2";
                }
            }
            return Json(query, JsonRequestBehavior.AllowGet);
        }

6.  Now, get all the scheduled graphics for the selected clip i.e., playout.

  public JsonResult GetScheduledGraphics(string pc)
        {
            dynamic graphics;
            /* check for graphics whether it exists for any of the playout, if 
             * it exists, then display all graphics for that clip.*/
            List<GraphicsMaster> scheduledGraphics = new List<GraphicsMaster>();
            List<int> graphicClipMapId = new List<int>();
            List<int> graphicsCode = new List<int>();
            List<GraphicsClipMap> graphicsId = new List<GraphicsClipMap>();
            List<string> graphicsOffset = new List<string>();
            List<string> graphicsDuration = new List<string>();

            List<int> clipMapId = new List<int>();
            graphicsId = context.GraphicsClipMaps.Where(y => y.playoutcode.Equals(pc)).ToList();
            if (graphicsId.Count > 0)
            {
                foreach (var gId in graphicsId)
                {
                    int id = Convert.ToInt32(gId.GraphicsId);
                    graphicsCode.Add(id);
                    clipMapId.Add(gId.GraphicsClipMapId);
                }
                for (int i = 0; i < clipMapId.Count; i++)
                {
                    int id = Convert.ToInt32(clipMapId[i]);
                    int gcode = Convert.ToInt32(graphicsCode[i]);
                    graphicClipMapId.Add(Convert.ToInt32(context.GraphicsClipMaps.Where(p => p.GraphicsId == id).Select(b => b.GraphicsClipMapId).FirstOrDefault()));
                    scheduledGraphics.Add(context.GraphicsMasters.Where(c => c.GraphicsId == gcode).FirstOrDefault());
                    graphicsOffset.Add(context.GraphicsClipMaps.Where(a => a.GraphicsClipMapId == id).Select(b => b.GraphicsOffset).FirstOrDefault().ToString());
                    graphicsDuration.Add(context.GraphicsClipMaps.Where(a => a.GraphicsClipMapId == id).Select(b => b.GraphicsDuration).FirstOrDefault().ToString());
                }
            }
            graphics = (new { PlayoutId = pc, GraphicsName = scheduledGraphics.Select(a => a.GraphicsName), GraphicStartTime = graphicsOffset, GraphicEndTime = graphicsDuration, GraphicsMapId = clipMapId });
            return Json(graphics, JsonRequestBehavior.AllowGet);
        }

7. Now, Update the Clip Details in the div to show graphics after deleting selected graphics. This is achieved using another ajax call within the delete ajax call i.e., showClipGraphics(clips);. Where in we pass the updated clips object after deleting the graphics from the clip.

This is achieved as under...

 function showClipGraphics(clips) {
        $('#clipDetails').empty();
        $('#clipDetails').append('<tr style="background-color:#20ff00"><th>Select</th><th>'
                    + 'Start Time</th><th>End Time</th><th>Duration</th><th>Title</th><th>File Server '
                    + 'Programme Id</th></tr>');
        for (var i = 0; i < clips.PlayoutId.length; i++) {
            if (clips.Prefix[i] == "FF" || clips.Prefix[i] == "MB" || clips.Prefix[i] == "SO") {
                $('#clipDetails').append('<tr style="background-color:#01ACFE"><td><input type="radio" class="rdoClip" name="rdoClipDetail" id="'
                 + clips.PlayoutId[i] + '" value="' + clips.PlayoutId[i] + '" onclick="selectedClip(this)" /></td><td>'
                 + clips.ClipStartTime[i].toString() + '</td><td>' + clips.ClipEndTime[i].toString() + '</td><td>'
                 + clips.ClipDuration[i].toString() + '</td><td>' + clips.ClipName[i].toString()
                 + '</td><td>' + clips.FileServerProgrammeId[i].toString() + '</td><td>'
                 + clips.Prefix[i].toString() + '</td></tr>');
                /* ajax call for getting all scheduled graphics within a clip */
                var playoutcode = clips.PlayoutId[i];
                if (playoutcode != null) {
                    var options = {};
                    options.url = '@Url.Action("GetScheduledGraphics", "GraphicsClipMap")';
                    options.data = JSON.stringify({ pc: playoutcode });
                    options.type = "POST";
                    options.dataType = "json";
                    options.contentType = "application/json";
                    options.async = false;
                    options.success = function (graphics) {
                        if (graphics.GraphicsName.length > 0) {
                            $('#clipDetails').append('<tr style="background-color:#F9FF00"><th colspan="3">Graphic for this clip</th><th>Graphics Name</th><th>Graphics Offset</th><th>Graphics Duration</th><th><input type="button" class="delButton" value="Delete" id="' + playoutcode + '" onclick=DeleteGraphicsFromClip('+playoutcode+')></th>');
                            for (var i = 0; i < graphics.GraphicsName.length; i++) {
                                $('#clipDetails').append('<tr style="background-color:#00FF9F"><td colspan="3">&nbsp</td><td>' + graphics.GraphicsName[i] + '</td><td>' + graphics.GraphicStartTime[i] + '</td><td>' + graphics.GraphicEndTime[i] + '</td><td><input type="checkbox" name="chkDelete" class="' + playoutcode + '" value="' + graphics.GraphicsMapId[i] + '" id=' + graphics.GraphicsMapId[i] + ' /></td></tr>');
                            }
                        }
                    };
                    options.error = function () { alert("Error retrieving scheduled graphics due to problem in ajax call!"); };
                    $.ajax(options);
                }
            }
            else {
                $('#clipDetails').append('<tr><td></td><td>' + clips.ClipStartTime[i].toString() + '</td><td>' + clips.ClipEndTime[i].toString() + '</td><td>' + clips.ClipDuration[i].toString() + '</td><td>' + clips.ClipName[i].toString() + '</td><td>' + clips.FileServerProgrammeId[i].toString() + '</td><td>' + clips.Prefix[i].toString() + '</td></tr>');
            }
        }
    }

In the above function, we retrieve all the clips and the graphics under that clip, if any, using ajax. Then we update the clipDetails div with the newly retrieved clip details.

Populate drop down via AJAX using MVC4 C# when page loads.

1. Create a view that contains one drop down list for displaying items into it.

2. In Controller write a method that return JsonResult. And don't forget to mention it as [HttpPost]     since we will be using AJAX POST method, Ajax data type as Json hence the return type of             method is JsonResult.

3. We will create a function loadChannels() that will be called when the document is ready. This is        achieved using Jquery as :- 
      $(document).ready(function(){
               //Function call goes here.
      });

4. The method that we have written in controller (NOTE STEP 2) which will return JsonResult will     get called via AJAX from the method loadChannels() (NOTE STEP 3).



View as FpcDetails.cshtml

@{
    ViewBag.Title = "FpcDetails";
    Layout = "~/Views/Shared/_LayoutPrivate.cshtml";
}
@using (Html.BeginForm("FpcDetails", "Fpc", FormMethod.Post, new { enctype = "multipart/form-data", id = "form" }))
{
        <table>
            <tr>
                <td>
                    Select Channel:
                </td>
                <td>
                    @Html.DropDownList("channelsList", new List<SelectListItem> { }, string.Empty, new {                                                                   @class = "DropDown", @id = "dropDownChannels" }
                                                        )
                </td>
            </tr>
        </table>

    <input type="hidden" id="hdnChannels" />
}

//Document.ready function calling loadChannels().

<script type="text/javascript">

    $(document).ready(function () {
        loadChannels();
    });

/* Defining loadChannels() function */

    /*Loading channels on page load*/
 
  function loadChannels() {
        var options = {};
/* url for ajax to call a method GetChannels in the controller Fpc that will return JsonResult */

        options.url = '@Url.Action("GetChannels", "Fpc")';

/* Method type of Ajax is POST. Same will be mentioned in controller GetChannels() method as [HttpPost] */
        options.type = "POST";

/* Type of Ajax is json. This will  be the return type of method defined in Controller.i.e., JsonResult. */

        options.dataType = "json";
        options.contentType = "application/json";

/* channels passed as argument in the function as used to get the returned values from the controller back to       the view. This will give us an List of Id and Name. Hence we need to iterate over it in order to display           them. */

        options.success = function (channels) {

/* Empty the drop down list before appending any new values. */

            $("#dropDownChannels").empty();
            $("#dropDownChannels").append("<option value=></option>");
            for (var i = 0; i < channels.length; i++) {
                $("#dropDownChannels").append("<option value=" + channels[i].Id + ">" + channels[i].Name +                                                                           "</option>");
            }
            $("#dropDownChannels").prop("disabled", false);
        };

/* If there is any problem in Ajax, error method will get invoked. */

        options.error = function () { alert("Error retrieving Channels!"); };
        $.ajax(options);
    }

</script>


Controller: 

/* Inside our controller we just add the following code. */

/*Get all Channels via AJAX */
        [HttpPost]
        public JsonResult GetChannels()
        {
            List<AMSChannel> channels;
            channels = context.AMSChannels.ToList();
            var result = (from x in channels select new { Id = x.ChannelId, Name = x.ChannelName });
            return Json(result, JsonRequestBehavior.AllowGet);
        }