1

I have a C# model that gets populated through its constructor. I would like to place this object in my _Layout.cshtml so my Javascript can use it as settings.

Here is what my model looks like:

public class SomeConfig
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
    public string PropertyC { get; set; }

    public SomeConfig()
    {
        PropertyA = SystemSettings.getSetting(KEYA);
        PropertyB = SystemSettings.getSetting(KEYB);
        PropertyC = SystemSettings.getSetting(KEYC);
    }
}

I would like to initialize and output this in _Layout.cshtml so all my other views can use it. So far I am only able to figure out how to do this manually in _Layout.cshtml like this:

<script type="text/javascript">
    MyNamespace.someConfig = {
        PropertyA: @SystemSettings.getSetting(KEYA),
        PropertyB: @SystemSettings.getSetting(KEYB),
        PropertyC: @SystemSettings.getSetting(KEYC)
    }
</script>

This is horrible because every time the SomeConfig.cs model gets extended, I have to remember to extend it manually client-side. Is there a way to initialize it in the _Layout.cshtml so it creates a Javascript object dynamically?

1
  • Json.Net is pretty good........ Commented May 15, 2012 at 18:21

1 Answer 1

8

Try instead to do

<script type="text/javascript">
    MyNamespace.someConfig =  @Json.Encode(SystemSettings);
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! I had to add Html.Raw(..) in front of it and worked great. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.