Question

I am building web app with .net, and I have a lot of settings and other data that I need to pass from the database with c# to JavaScript and use it with JavaScript. What that I am doing now is to store all the data in array in c# and then pass it to JavaScript as array. The problem is that I need to remember for each setting the index in the array. So I want to pass from c# some JavaScript object like this:

Settings{ Height: "67", Width:"2.5", Etc.. } And than get the setting with only knowing the name like: var height = settings.height

Is there a way to create this kind of object in c#, and to use its in js?

Was it helpful?

Solution

U can use System.Web.Helpers.Json.Encode() method to serialize your object to json string. And in your javascript you can use $.parseJSON(jsonString) to deserialize it and use like javascript object.

public class Settings {
    public double Width {get;set;}
    public double Height {get;set;}

    public string ToJson()
    {
        return Json.Encode(this);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top