需要将C#中的键值对传递给Javascript

时间:2013-08-16 19:00:53

标签: c# javascript asp.net-mvc json

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

2 个答案:

答案 0 :(得分:4)

这是我可能会做的......

运行此控制台应用程序并查看其功能:

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”部分,请参阅此处Making a Simple Ajax call to controller in asp.net mvc以获取有关MVC和jQuery的实际示例。

答案 1 :(得分:1)

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

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