简体   繁体   English

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

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

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. 对于“传递给javascript”部分,请参见此处在asp.net mvc中控制器进行简单的Ajax调用,以获取MVC和jQuery的实际示例。

Yes you can use JSON. 是的,您可以使用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: 或如上述答案@ user1477388一样,将keyvalupairs序列化为Json并返回如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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