0

In C# I do this from a controller:

public ActionResult GetCompanies()
{
    var vm = new CompanyViewModel { jsonData = JsonConvert.Serialize(_repository.All<Company>()) };

    return View(vm);
}

ViewModel looks like this:

public CompanyViewModel
{
    public string jsonData {get;set}
}

On the client side:

@model MyWebApp.ViewModels.CompanyViewModel

@Scripts.Render("~/bundles/knockout")
<script type="text/javascript">
   var serverData = <!-- Many Things To Do Here -->
</script>

In the part <!-- Many Things To Do Here --> there a few things you can do to put the server data into a JavaScript Object.

What is the best way to do this, because I have had problems with JSON.parse to do with some characters JSON.NET serializes.

Is just putting the plain data in there okay (it works): var serverData = @Html.Raw(@Model.jsonData)

What other things should/can be done here?

2
  • Why send a string if you are trying to parse it into JSON on the client. You are already sending JSON back to the client, just make jsonData a real .NET object on the server that can be serialized to the client. Commented Jun 26, 2014 at 18:42
  • I'm asking what is acceptable to serialize a C# object into a set of JavaScript objects. Commented Jun 27, 2014 at 11:43

1 Answer 1

1

Rather than creating a model just to hold a JSON string, just pass the plain .NET object to your view, and serialize it to JSON there:

In your controller:

public ActionResult GetCompanies()
{
    return View(_repository.All<Comapny>());
}

Then in your view:

<script>
    var companies = @Html.Raw(JsonConvert.SerializeObject(Model));
</script>

If you want/need a strongly typed model in your view, you should change your CompanyViewModel to this:

public class CompanyViewModel
{
    public IList<Company> Companies {get; set;}
    //Or whatever sort of collection your repository returns
}

And in your controller

public ActionResult GetCompanies()
{
    var vm = new CompanyViewModel { Companies = _repository.All<Company>() };
    return View(vm);
}

Then in your view:

@model MyWebApp.ViewModels.CompanyViewModel
<script>
    var companies = @Html.Raw(JsonConvert.SerializeObject(Model.Companies));
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

So you are saying that you can just set a variable to converted JSON then?

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.