davidjosepha
davidjosepha

Reputation: 117

Need to pass key-value pairs from C# to Javascript

I need to pass a variable from C# to javascript in the form { 'key':'value', ..., }. I tried passing it as a string and hoping javascript would parse it (because the C# on cshtml pages is evaluated server side and js is client side) but unfortunately the quotes were formatted as &whateverthecodeis; so it didn't work. I think JSON might be what I'm looking for, but I have no idea how to use it.

Upvotes: 1

Views: 2729

Answers (2)

Yes you can use JSON. Perhaps you should try using escape characters to escape the quotes being misinterpreted. Or as in the above answer @user1477388, serialize the keyvalupairs to Json and return as following:

  public ActionResult ReturnJsonObject()
 {
    //Your code goes here
    return Json(json);
}

Upvotes: 1

user1477388
user1477388

Reputation: 21420

Here is what I might do...

Run this console app and see what it does:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// note: you will have to include a reference to "System.Web.Extensions" in your project to be able to use this...
using System.Web.Script.Serialization;

namespace KeyValuePairTestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("MyFirstKey", "MyFirstValue"),
                new KeyValuePair<string, string>("MySecondKey", "MySecondValue")
            };

            string json = new JavaScriptSerializer().Serialize(pairs);

            Console.WriteLine(json);
        }
    }
}

For the "pass to javascript" part, please see here Making a Simple Ajax call to controller in asp.net mvc for practical examples for MVC and jQuery.

Upvotes: 3

Related Questions