Tuesday, November 15, 2011

Use C# constants in Javascript

GlobalConstants.cs:
---------------------
namespace Utility
{
    public static class GlobalConstants
    {
        public const string SecurtityKey = "gkjhhkjhykhihfsdjhglkjhgkdfjlghdsfklghfdgeriutyrthvbfkjghdfklghdfskghrtguiutert";
    }
}

InviteUser.chtml:
--------------
<script type="text/javascript" src="@Url.Action("GlobalConstants")"></script>
<script type="text/javascript">
alert(constants.SecurtityKey);
</script>

UserManagementController.cs:
--------------------------------

        public ActionResult GlobalConstants()
        {
            var constants = typeof(BasePage)
                .GetFields()
                .ToDictionary(x => x.Name, x => x.GetValue(null));
            var json = new JavaScriptSerializer().Serialize(constants);
            return JavaScript("var constants = " + json + ";");
        }

Wednesday, September 21, 2011

Get ViewBag value from javascript

<script type="text/javascript">
var roleExist = @Html.Raw(Json.Encode(Model.UserRolePropertyLevel));
var array = @Html.Raw(Json.Encode(@ViewBag.AvailablePPOList));
alert(JSON.stringify(roleExist));
</script>

Wednesday, September 14, 2011

Sorting Array List

http://www.javascriptkit.com/javatutors/arraysort2.shtml

http://www.sitepoint.com/javascript-array-sorting/

Javascript protoType

http://www.codeproject.com/KB/scripting/Observer_Pattern_JS.aspx

function ArrayList() {
            //initialize with an empty array
            this.aList = [];
        }

        ArrayList.prototype =
        {
            Count: function () {
                return this.aList.length;
            },
            Add: function (object) {
                //Object are placed at the end of the array
                return this.aList.push(object);
            },
            GetAt: function (index) //Index must be a number
            {
                if (index > -1 && index < this.aList.length)
                    return this.aList[index];
                else
                    return undefined; //Out of bound array, return undefined
            },
            Clear: function () {
                this.aList = [];
            },
            RemoveAt: function (index) // index must be a number
            {
                var m_count = this.aList.length;

                if (m_count > 0 && index > -1 && index < this.aList.length) {
                    switch (index) {
                        case 0:
                            this.aList.shift();
                            break;
                        case m_count - 1:
                            this.aList.pop();
                            break;
                        default:
                            var head = this.aList.slice(0, index);
                            var tail = this.aList.slice(index + 1);
                            this.aList = head.concat(tail);
                            break;
                    }
                }
            },
            Insert: function (object, index) {
                var m_count = this.aList.length;
                var m_returnValue = -1;

                if (index > -1 && index <= m_count) {
                    switch (index) {
                        case 0:
                            this.aList.unshift(object);
                            m_returnValue = 0;
                            break;
                        case m_count:
                            this.aList.push(object);
                            m_returnValue = m_count;
                            break;
                        default:
                            var head = this.aList.slice(0, index - 1);
                            var tail = this.aList.slice(index);
                            this.aList = this.aList.concat(tail.unshift(object));
                            m_returnValue = index;
                            break;
                    }
                }
                return m_returnValue;
            },
            IndexOf: function (object, startIndex) {
                var m_count = this.aList.length;
                var m_returnValue = -1;

                if (startIndex > -1 && startIndex < m_count) {
                    var i = startIndex;

                    while (i < m_count) {
                        if (this.aList[i] == object) {
                            m_returnValue = i;
                            break;
                        }

                        i++;
                    }
                }
                return m_returnValue;
            },
            LastIndexOf: function (object, startIndex) {
                var m_count = this.aList.length;
                var m_returnValue = -1;

                if (startIndex > -1 && startIndex < m_count) {
                    var i = m_count - 1;

                    while (i >= startIndex) {
                        if (this.aList[i] == object) {
                            m_returnValue = i;
                            break;
                        }

                        i--;
                    }
                }
                return m_returnValue;
            },
            ConvertToJSON: function () {
                return JSON.stringify(this.aList);
            },
            AscSort: function () {
                this.aList.sort(function (firstObject, secondObject) {
                    if (firstObject.PropertyName < secondObject.PropertyName)
                        return -1;
                    if (firstObject.PropertyName > secondObject.PropertyName)
                        return 1;
                    return 0;
                })
            }
        };


function PropertyLevel() {
    this.PropertyId = "";
    this.PropertyName = "";
    this.PropertyValue = [];
}



        var myarrayobject = new ArrayList();
        function CreateRoleProperty(propertyName, propertyId, propertyValueKey, propertyValueText) {
            var objPropertyLevel = new PropertyLevel();
            objPropertyLevel.PropertyId = propertyId;
            objPropertyLevel.PropertyName = propertyName;
            var PropertyValue = new ListEntity();
            PropertyValue.Key = propertyValueKey;
            PropertyValue.Value = propertyValueText;
            objPropertyLevel.PropertyValue[0] = PropertyValue;
            // Add values at the end of the array
            myarrayobject.Add(objPropertyLevel);

           // Ascending Order
          myarrayobject.AscSort();
        }

remove Last Character

myStr = myStr.slice(0, -1)

Tuesday, August 30, 2011

CheckBoxList in MVC

http://blogs.msdn.com/b/miah/archive/2008/11/10/checkboxlist-helper-for-mvc.aspx

http://weblogs.asp.net/gunnarpeipman/archive/2011/05/05/asp-net-mvc-implementing-checkboxlist.aspx

MVC Web Grid


                        @{
                            var grid = new WebGrid(ViewBag.AvailableCAList1, canPage: false, canSort: false);
                            @grid.GetHtml(tableStyle: "webGrid",
                            htmlAttributes: new { id = "DataTable" },
                             columns: grid.Columns(
                                    grid.Column("Ca_Id", header: "Select", format: @<text><input name="chk" type="checkbox" checked="@item.Selected" value="@item.Ca_Id"/></text>),
                                    grid.Column("Selected", "Select", format: (item) => Html.CheckBox("chkSelect", (Boolean)item.Selected, new { @id = item.Ca_Id, @value = item.Ca_Description })),
                                    grid.Column(format: (item) => Html.ActionLink("Edit", "EditProject", new { EmployeeID = item.Ca_Id })),
                                    grid.Column("Ca_Id", header: "CA"),
                                    grid.Column("Ca_Description", header: "Description"),
                                    grid.Column("Selected"),
                                    grid.Column("Ca_Id", header: "CA1", format: @<text><input name="Amount" type="text" value="@item.Ca_Id" /></text>)
                             ));              
                        }


ViewBag.AvailableCAList1 = finding.GetAvailableCA1(objFindingModel.EpasCode.EpasCodeId);


        public List<CA> GetAvailableCA1(int id)
        {
            List<CA> objCA = new List<CorrectiveAction>();
            DbCommand dbCommand = oDatabase.GetStoredProcCommand("GetAvailable");
            oDatabase.AddInParameter(dbCommand, "@id", DbType.Int32, id);
            using (System.Data.IDataReader oReader = oDatabase.ExecuteReader(dbCommand))
            {
                while (oReader.Read())
                {
                    objCA .Add(new CA
                    {
                        Ca_Id = Convert.ToInt32(oReader["id"].ToString()),
                        Ca_Description = oReader["text"].ToString(),
                        Selected = (Convert.ToInt32(oReader["available_CA_Id"].ToString()) % 2) == 0 ? true : false,
                    }
                    );
                }
            }
            return objCA ;
        }

Wednesday, August 24, 2011

Moving data between two ListBoxes


<form method="get">             
      <select id="SelectLeft" multiple="multiple">
            <option value="1">Australia</option>
            <option value="2">New Zealand</option>
            <option value="3">Canada</option>
            <option value="4">USA</option>
            <option value="5">France</option>
      </select>
           
      <input id="MoveRight" type="button" value=" >> " />
      <input id="MoveLeft" type="button" value=" << " />
       
      <select id="SelectRight" multiple="multiple">          
      </select>
</form>
jQuery 1.3.2
Below is the code to move the selected items from each <select> element. 
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>   
    <script language="javascript" type="text/javascript">
        $(function() {
            $("#MoveRight,#MoveLeft").click(function(event) {
                var id = $(event.target).attr("id");
                var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
                var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";
 
                var selectedItems = $(selectFrom + "option:selected");
                var output = [];               
                $.each(selectedItems, function(key, e) {                   
                  output.push('<option value="' + e.value + '">' + e.text + '</option>');
                                });
               
                $(moveTo).append(output.join(""));               
                selectedItems.remove();
            });
        });
    </script>
jQuery 1.4
 
In the new jQuery library, the team has introduced a new function called toArray. This retrieves all the DOM elements contained in the jQuery set, as an array. So here's the code below:
 
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
    <script language="javascript" type="text/javascript">
        $(function() {
            $("#MoveRight,#MoveLeft").click(function(event) {
                var id = $(event.target).attr("id");
                var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
                var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";
 
                var selectedItems = $(selectFrom + " :selected").toArray();
                $(moveTo).append(selectedItems);
                selectedItems.remove;
            });
        });
    </script> 

Saturday, June 18, 2011

Get Dropdown title

    $("#drpGuide option").attr("title")
    $("#drpGuide option:selected").attr("title")

Tuesday, June 7, 2011

Call WCF Service using jQuery

// Javascript

var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;

function CallService() {
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        success: function (msg) {//On Successfull service call
            ServiceSucceeded(msg);
        },
        error: ServiceFailed// When Service call fails
    });
}

function ServiceSucceeded(result) {
    alert("muthuvel");
    if (DataType == "json") {
        resultObject = result.GetUserResult;
        for (i = 0; i &lt; resultObject.length; i++) {
            alert(resultObject[i]);
        }
    }
}

function ServiceFailed(xhr) {
    alert("Failed");
    alert(xhr.responseText);
    if (xhr.responseText) {
        var err = xhr.responseText;
        if (err)
            error(err);
        else
            error({ Message: "Unknown server error." })
    }
    return;
}

function getName() {
    var uesrid = "1";
    Type = "POST";
    Url = "Services/Service.svc/GetUser";
    Data = '{"Id": "' + uesrid + '"}';
    ContentType = "application/json; charset=utf-8";
    DataType = "json"; ProcessData = true;
    CallService();
}


// WCF Service
// Service.svc


using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Activation;

namespace AssessmentmanagerHTML5
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service : IService
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }


        public string[] GetUser(string Id)
        { return new User().GetUser(Convert.ToInt32(Id)); }
    }

    public class User
    {

        Dictionary users = null;
        public User()
        {
            users = new Dictionary();
            users.Add(1, "pranay");
            users.Add(2, "Krunal");
            users.Add(3, "Aditya");
            users.Add(4, "Samir");
        }

        public string[] GetUser(int Id)
        {
            var user = from u in users
                       where u.Key == Id
                       select u.Value;

            return user.ToArray();
        }
    }
}


// IService
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

namespace AssessmentmanagerHTML5
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
        string GetData(int value);

        [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
        string[] GetUser(string Id);
    }
}