.

jQuery & jQuery.UI available test

The following code block:

<script>
    if (typeof jQuery != 'undefined') {
        // jQuery is loaded => print the version
        alert(jQuery.fn.jquery);
    } else {
        alert('jQuery is NOT loaded');
    }

    $(document).ready(function() {
        if (jQuery.ui) {
        } else {
            alert('jQuery.UI is NOT loaded!!');
        }
    });
</script>

will either print the JQuery version or inform you if no JQuery library is found.
also warn if jQueryUI is not loaded

Convert Json To Xml

code

var jsonOutput = @"{""Feeds"":[{""InstrumentName"":""Natural Gas"",""DailyHigh"":3.497,""DailyLow"":3.439,""Change"":0.15882183078255849,""InstrumentID"":123,""BuyRate"":3.471,""SellRate"":3.466},{""InstrumentName"":""Heating Oil"",""DailyHigh"":3.0944,""DailyLow"":3.0436,""Change"":0.70009768804949535,""InstrumentID"":430,""BuyRate"":3.0935,""SellRate"":3.0915}],""Type"":11}";
var myelement = JsonConvert.DeserializeXmlNode(jsonOutput, "ThisGetsIgnored").FirstChild; //Newtonsoft.Json.JsonConvert
var xml = myelement.InnerXml;
Console.WriteLine(xml);

input

{
   "Feeds":[
      {
         "InstrumentName":"Natural Gas",
         "DailyHigh":3.497,
         "DailyLow":3.439,
         "Change":0.15882183078255849,
         "InstrumentID":123,
         "BuyRate":3.471,
         "SellRate":3.466
      },
      {
         "InstrumentName":"Heating Oil",
         "DailyHigh":3.0944,
         "DailyLow":3.0436,
         "Change":0.70009768804949535,
         "InstrumentID":430,
         "BuyRate":3.0935,
         "SellRate":3.0915
      }
   ],
   "Type":11
}

output

<Feeds>
  <InstrumentName>Natural Gas</InstrumentName>
  <DailyHigh>3.497</DailyHigh>
  <DailyLow>3.439</DailyLow>
  <Change>0.15882183078255849</Change>
  <InstrumentID>123</InstrumentID>
  <BuyRate>3.471</BuyRate>
  <SellRate>3.466</SellRate>
</Feeds>
<Feeds>
  <InstrumentName>Heating Oil</InstrumentName>
  <DailyHigh>3.0944</DailyHigh>
  <DailyLow>3.0436</DailyLow>
  <Change>0.70009768804949535</Change>
  <InstrumentID>430</InstrumentID>
  <BuyRate>3.0935</BuyRate>
  <SellRate>3.0915</SellRate>
</Feeds>
<Type>11</Type>

Deserializing Json

[TestMethod]
public void Deserialize_Concrete()
{
    string json =
        @"[{""Feeds"":[{""InstrumentName"":""Natural Gas"",""DailyHigh"":3.497,""DailyLow"":3.439,""Change"":0.15882183078255849,""InstrumentID"":123,""BuyRate"":3.471,""SellRate"":3.466},{""InstrumentName"":""Heating Oil"",""DailyHigh"":3.0944,""DailyLow"":3.0436,""Change"":0.70009768804949535,""InstrumentID"":430,""BuyRate"":3.0935,""SellRate"":3.0915}],""Type"":11}]";
    var serializer = new JavaScriptSerializer();
    var qwer = serializer.Deserialize<List<FeedbackReport>>(json);
}

[Serializable]
public class FeedbackReport
{
    public List<Feed> Feeds;
}

[Serializable]
public class Feed
{
    public float BuyRate;
    public float Change;
    public float DailyHigh;
    public float DailyLow;
    public string InstrumentID;
    public string InstrumentName;
    public float SellRate;
}

[TestMethod]
public void Deserialize_Dynamically()
{
    string json =
        @"[{""Feeds"":[{""InstrumentName"":""Natural Gas"",""DailyHigh"":3.497,""DailyLow"":3.439,""Change"":0.15882183078255849,""InstrumentID"":123,""BuyRate"":3.471,""SellRate"":3.466},{""InstrumentName"":""Heating Oil"",""DailyHigh"":3.0944,""DailyLow"":3.0436,""Change"":0.70009768804949535,""InstrumentID"":430,""BuyRate"":3.0935,""SellRate"":3.0915}],""Type"":11}]";

    var serializer = new JavaScriptSerializer();  //System.Web.Script.Serialization.JavaScriptSerializer

    //might perhaps need the following line - not always
    //serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

    var DeserializedObj = serializer.Deserialize(json, typeof(object));
}

Json.Decode

<code>Ensure your project "<code>properties</code>" is set to
".NET Framework 4"  (not the Client Profile version)</code>

Add a “.Net” reference:
System.Web.Helpers (2.0.0.0) (v4.0.30319)

include your reference:

using System.Web.Helpers;

 

and deserialize:

var dynamicObject = Json.Decode(jsonString);

alternatively, without dynamics, just a dictionary:

var deserializedString = new JavaScriptSerializer().Deserialize<Dictionary<string, Dictionary<string, int>>>(val);
var myVals = deserializedString["mainkey"];

and getting results:

foreach (string key in myVals.Keys)
    Console.WriteLine(key + ": " + myVals[key]);

or use json.net

JQuery vsdoc Visual Studio intellisense

To enable the vsdoc intellisense. Reference the file in your page as follow:

<% if(false) 
{ %>
    <script src="/path/to/jquery-1.8.1-vsdoc.js" type="text/javascript"></script>
<% } %>

It is wrapped in if(false) to prevent the reference from being rendered.

And at the top of your javascript (.js) file:

/// <reference path="/path/to/jquery-1.8.1-vsdoc.js" />

IE7 specific styles

      &lt;!--[if IE 7]&gt;
            &lt;script src="@Url.Content("~/Scripts/json2.js")" type="text/javascript"&gt;&lt;/script&gt;
      &lt;![endif]--&gt;

<a href="http://blog.bitlinkit.com/wp-content/uploads/2013/04/json2.js">json2</a>

JSON serialization

//This is just used to serialize the results to the file as JSON and read it back
private static string ToJson(T obj)
{
MemoryStream stream = new MemoryStream();

try
{
DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof (T));
jsSerializer.WriteObject(stream, obj);

return Encoding.UTF8.GetString(stream.ToArray());
}
finally
{
stream.Close();
stream.Dispose();
}
}

private static T FromJson(string input)
{
MemoryStream stream = new MemoryStream();

try
{
DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof (T));
stream = new MemoryStream(Encoding.UTF8.GetBytes(input));
T obj = (T) jsSerializer.ReadObject(stream);

return obj;
}
finally
{
stream.Close();
stream.Dispose();
}
}

DynamicJsonConverter : JavaScriptConverter

    public sealed class DynamicJsonConverter :  JavaScriptConverter
    {
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");

            return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override IEnumerable<Type> SupportedTypes
        {
            get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(object) })); }
        }

        #region Nested type: DynamicJsonObject

        private sealed class DynamicJsonObject : DynamicObject
        {
            private readonly IDictionary<string, object> _dictionary;

            public DynamicJsonObject(IDictionary<string, object> dictionary)
            {
                if (dictionary == null)
                    throw new ArgumentNullException("dictionary");
                _dictionary = dictionary;
            }

            public override string ToString()
            {
                var sb = new StringBuilder("{");
                ToString(sb);
                return sb.ToString();
            }

            private void ToString(StringBuilder sb)
            {
                var firstInDictionary = true;
                foreach (var pair in _dictionary)
                {
                    if (!firstInDictionary)
                        sb.Append(",");
                    firstInDictionary = false;
                    var value = pair.Value;
                    var name = pair.Key;
                    if (value is string)
                    {
                        sb.AppendFormat("{0}:\"{1}\"", name, value);
                    }
                    else if (value is IDictionary<string, object>)
                    {
                        new DynamicJsonObject((IDictionary<string, object>)value).ToString(sb);
                    }
                    else if (value is ArrayList)
                    {
                        sb.Append(name + ":[");
                        var firstInArray = true;
                        foreach (var arrayValue in (ArrayList)value)
                        {
                            if (!firstInArray)
                                sb.Append(",");
                            firstInArray = false;
                            if (arrayValue is IDictionary<string, object>)
                                new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);
                            else if (arrayValue is string)
                                sb.AppendFormat("\"{0}\"", arrayValue);
                            else
                                sb.AppendFormat("{0}", arrayValue);

                        }
                        sb.Append("]");
                    }
                    else
                    {
                        sb.AppendFormat("{0}:{1}", name, value);
                    }
                }
                sb.Append("}");
            }

            public override bool TryGetMember(GetMemberBinder binder, out object result)
            {
                if (!_dictionary.TryGetValue(binder.Name, out result))
                {
                    // return null to avoid exception.  caller can check for null this way...
                    result = null;
                    return true;
                }

                var dictionary = result as IDictionary<string, object>;
                if (dictionary != null)
                {
                    result = new DynamicJsonObject(dictionary);
                    return true;
                }

                var arrayList = result as ArrayList;
                if (arrayList != null && arrayList.Count > 0)
                {
                    if (arrayList[0] is IDictionary<string, object>)
                        result = new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x)));
                    else
                        result = new List<object>(arrayList.Cast<object>());
                }

                return true;
            }
        }

        #endregion
    }

 

 

 

 

 

    public class Json
    {
        public static dynamic DeserializeMemorySteamToObject(HttpRequestBase request)
        {
            var json = string.Empty;
            using (var reqMemStream = new StreamReader(request.InputStream))
            {
                json = reqMemStream.ReadToEnd();
            }

            var serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
            return (dynamic)serializer.Deserialize(json, typeof(object));
        }

    }
        [HttpPost]
        public ActionResult UpdatePatientDetails()
        {
            var obj = PasPlus.Core.Json.DeserializeMemorySteamToObject(Request);

            var patientId = obj.patientId;
            var patient = new PasPlus.BusinessObjects.Core.Patients(patientId.ToString());

            patient.Surname = obj.surname;
            patient.Forname = obj.forname;
            patient.Other_names = obj.otherNames;
            patient.Postcode = obj.postcode;
            patient.Telephone_home = obj.telephoneHome;
            patient.Telephone_mobile = obj.telephoneMobile;
            patient.Telephone_work = obj.telephoneWork;
            patient.Email = obj.email;
            patient.Next_of_kin = obj.nextOfKin;
            patient.Next_of_kin_tel = obj.nextOfKinPhone;

            patient.Save();
            return null;
        }
<script type="text/javascript">
    $(document).ready(function () {
        //set date format of date picker string
        $(function () {
            $("#dobTextBox").datepicker({ dateFormat: 'dd/mm/yy' });
        });

        $('#CloseButton').click(function (index) {
            $('#dialogBox').dialog('destroy').remove();
        });

        $("#SaveButton").click(function () {
            //create json 
            var patientId = $('#patientIdHiddenField').val();
            var surname = $('#surnameTextBox').val();
            var forname = $('#fornameTextBox').val();
            var otherNames = $('#otherNamesTextBox').val();
            var postcode = $('#postcodeTextBox').val();
            var telephoneHome = $('#telephoneHomeTextBox').val();
            var telephoneMobile = $('#telephoneMobileTextBox').val();
            var telephoneWork = $('#telephoneWorkTextBox').val();
            var email = $('#emailTextBox').val();
            var nextOfKin = $('#nextOfKinTextBox').val();
            var nextOfKinPhone = $('#nextOfKinPhoneTextBox').val();

            var json = JSON.stringify({
                patientId: patientId,
                surname: surname,
                forname: forname,
                otherNames: otherNames,
                postcode: postcode,
                telephoneHome: telephoneHome,
                telephoneMobile: telephoneMobile,
                telephoneWork: telephoneWork,
                email: email,
                nextOfKin: nextOfKin,
                nextOfKinPhone: nextOfKinPhone
            });

            var uri = '../los/Update/UpdatePatientDetails/';

            $('#dialogBox').empty().dialog('destroy');

            $.post(uri, json, function () {
                $(window.location.reload());
                //callback function for success
            });

            $(window.location.reload());
        });
    });
</script>

working with JQuery checkboxes – append to array

checking if a checkbox is checked and append it’s data value to an array:

 $(':checkbox').each(function () {
    var allPEtasks = new Array();
    var count = 0;
    var cb = $(this);
    if (cb.attr('checked'))  {
        var TaskId = cb.data('taskid');
        if (TaskId != null) {
                allPEtasks[count] = TaskId;
                count++;
            }
    }
});

this could be the razor view generating the html:

    foreach (var @tt in Model)
    {
        if ((tt.Task_commence_date != null) && (tt.Task_completed_date == null))
        {
            <div  class="TrafficLight_@(((TaskResultCode) @tt.TaskResultCode).ToString())" >@tt.Task_description 
            <input type="checkbox" data-petaskid="@tt.Patient_episode_task_id" />
            </div>
        }
    }

sending a JSON object on button click event

 

    $("#SaveButton").click(function () {

        //create json 
        var patientId = $('#patientIdHiddenField').val();
        var surname = $('#surnameTextBox').val();
        var forname = $('#fornameTextBox').val();
        var otherNames = $('#otherNamesTextBox').val();
        var postcode = $('#postcodeTextBox').val();
        var telephoneHome = $('#telephoneHomeTextBox').val();
        var telephoneMobile = $('#telephoneMobileTextBox').val();
        var telephoneWork = $('#telephoneWorkTextBox').val();
        var email = $('#emailTextBox').val();
        var nextOfKin = $('#nextOfKinTextBox').val();
        var nextOfKinPhone = $('#nextOfKinPhoneTextBox').val();

        var json = JSON.stringify({
            patientId: patientId,
            surname: surname,
            forname: forname,
            otherNames: otherNames,
            postcode: postcode,
            telephoneHome: telephoneHome,
            telephoneMobile: telephoneMobile,
            telephoneWork: telephoneWork,
            email: email,
            nextOfKin: nextOfKin,
            nextOfKinPhone: nextOfKinPhone
        });

        var uri = '../los/popup/UpdatePatientDetails/';

        $('#dialogBox').empty().dialog('destroy').remove();;

        $.post(uri, json, function () {
            //callback function for success
            $(window.location.reload());
        });

        $(window.location.reload()); 
    });
});