需要将键值对从C#传递到Javascript

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

本文关键字:Javascript 键值对      更新时间:2023-09-26

我需要将一个变量从C#传递给javascript,格式为{'key':'value',…,}。我试着把它作为字符串传递,希望javascript能解析它(因为cshtml页面上的C#是在服务器端评估的,js是在客户端评估的),但不幸的是,引号的格式是&whateverthecodeis;所以它不起作用。我认为JSON可能是我想要的,但我不知道如何使用它。

以下是我可能要做的…

运行这个控制台应用程序,看看它能做什么:

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

关于"传递到javascript"部分,请参阅此处在asp.net mvc中对控制器进行简单Ajax调用,以获得mvc和jQuery的实际示例。

是的,您可以使用JSON。也许你应该尝试使用转义符来避免被误解的引号。或者,如上面的答案@user1477388所示,将keyvalupairs序列化为Json,并返回如下:

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