Announcement

Thursday, 27 March 2014

How to create a connection string from Web.config file using stored procedure?

ConnectionStringInWeb.ConfigFile techiners.in
This post will illustrate how to create a database connection in C# using web.config file in MVC along with the reusable function for executing the stored procedure.


1. Create a connection string in web.config file or copy the code given below. Put this code in your <configuration> </configuration> part.


Wednesday, 26 March 2014

How to get checked items using jquery?

This DeleteGraphicsFromClip() function is called on the click event of Delete button whose id is deleteGraphicsFromClip.

The function will iterate over all the check boxes present in the form or in table <td> tag using jquery as $('input[name=chkDelete]:checked').each(function (){...}.

If the check box is checked, then get the id of the checked checkbox and set the flag to 0.

If there are no checked checkboxes, then set the flag to 1 for displaying error.

ids is declared as an array, and hence we use push method to insert the id of the checked checkbox.

Finaly, if the flag is 0, then do the required operation as passing the all checked ids to the controller for deleting the records. If the flag is 1, then display alert to the user to select atleast one checkbox for deleting.

 function DeleteGraphicsFromClip() {
        var ids = [];
        var flag=1;
        $('input[name=chkDelete]:checked').each(function () {
            if ($('input[name=chkDelete]:checked').length <= 0) {
                flag = 1;
            }
            else {
                ids.push($(this).attr("id"));
                flag = 0;
            }
        });
        if (flag==0) {
            alert('checked: ' + ids);
            flag = 1;
        }
        else {
            alert('Please select graphics to delete');
            flag = 1;
        }
    }

Friday, 21 March 2014

How to prevent the default action of submit button?

This is my submit button with id as "btnSubmitModification" .

We need to prevent the default action of this submit button i.e., to prevent the
form from submission on click of this button.

<input type="submit" class="button" id="btnSubmitModification" value="Save"/>

Here is the code in script tag.
This is achieved using jquery.

We handle the click event of submit button and pass the parameter to the
event handler function as e.

This is parameter is than used to prevent the default action of submit button i.e., to
prevent the form from submission.

Just write e.preventDefault(); and you are done.

<script type="text/javascript">
    $('#btnSubmitModification').click(function (e) {
        if ($("#txtName").val() != "" && $("#txtName").val() != null) {
            // write your further code here.
            return true;
        }
        else {
            alert('Please enter name.');
            e.preventDefault();
        }
    });
</script>

Alternative way to do the same thing is as: Just write return false and don't pass any
argument to the function.

<script type="text/javascript">
    $('#btnSubmitModification').click(function () {
        if ($("#txtName").val() != "" && $("#txtName").val() != null) {
            // write your further code here.
            return true;
        }
        else {
            alert('Please enter name.');
            return false;
        }
    });
</script>



Tuesday, 18 March 2014

Add items from one drop down to another drop down using jquery

1. Define a function that will move items from one drop down to another drop down.

2. This function will be called on the click of buttons i.e., Button for removing item and Button for       adding item.

3. The function accepts two parameters i.e., fromDropdown and toDropdown. It will move items           from fromDropdown to toDropdown.

4. The .off() method removes event handlers that were attached with .on(). See the discussion of         delegated and directly bound events on that page for more information. Calling .off() with no           arguments removes all handlers attached to the elements. Specific event handlers can be                 removed on elements by providing combinations of event names, namespaces, selectors, or             handlers function names.
 
    It basically removes an event handlers. For more information Click here.

Function for adding and removing items from one drop down to another drop down.

   function cutAndPaste(from, to) {
        $(to).append(function () {
            return $(from + " option:selected").each(function () {
                this.outerHTML;
            }).remove();
        });
   }

On click of Add button.

    $("#btnAdd").off("click").on("click", function (e) {
        var itemExists = false;
        var txt = $("#fromDropDown").val();
        e.preventDefault();
        $("#toDropDown option").each(function () {
            if ($(this).val() == txt) {
                itemExists = true;
                alert('Items already exists.');
                return false;
            }
        });
        if ($('#fromDropDown').val() == null) {
            alert('Item list is empty.')
        }
        if (!itemExists) {
            cutAndPaste("#fromDropDown", "#toDropDown");
        }
    });

On click of Remove button.

    $("#btnRemove").off("click").on("click", function (e) {
        var itemExists = false;
        var txt = $("#toDropDown").val();
        e.preventDefault();
        if ($("#toDropDown :selected").val() > 0) {
            cutAndPaste("#toDropDown", "#fromDropDown");
        }
        else {
            alert('Item does not exists');
            return false;
        }
    });

Friday, 14 March 2014

Get the total number of items of drop down using jquery


DropDownId is the id of the DropDown whose items you would like to count.

var items = $('#DropDownId>option').length;

Monday, 10 March 2014

Shutdown PC with Timer

How to shutdown a PC with Timer?

Follow these simple steps:

In windows XP

1. Goto Run>Command Prompt
2. Type the following code: shutdown -s -t xxxx
3. Press Enter. Your PC is scheduled to shutdown after xxxx seconds.

In Windows 7

Click Windows icon, type shutdown -s -t xxxx in the search box at the bottom.

Please Note: xxxx is the time in seconds.

To abort the automatic shutdown use the following code:

shutdown -a

Thursday, 6 March 2014

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);
        }