简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM