2

I have a strongly typed View that accepts a Customer model, this customer model is a LINQ2SQL partial class that has a property called Journeys which returns all Journeys that are associated with this Customer.

I was wondering if it would be possible to access the Customer.Journeys property as a JSON object from within the Javascript.

Is this possible? If so how would I go about accessing it? Would I be best to create a FormViewModel and store the Customer details and Journey details as a JSON object there and pass it to the javascript function using something like:

<% MyJavascriptFunction(Model.JSONJourneys) %>

Or should I alter the Journeys partial class and add a .ToJson() property? Or something completely different?

Thanks.

0

3 Answers 3

7

I would do this:

Using NewtonSoft Json Library, you can convert any C# model object to Json at the client end

http://james.newtonking.com/pages/json-net.aspx

in the view

<script>

var jsobject = <%= JsonConvert.SerializeObject(Model.Journeys) %>;

function myfunction (){ 
  //work with object

}

</script>
Sign up to request clarification or add additional context in comments.

Comments

2

How about exposing your Customer model through a Javascript view and loading it as a regular javascript file in your HTML?

Like this:

In your HTML view:

<script type="text/javascript" src="/customers/123/json">

And in your controller:

public ActionResult CustomerJson(int customerId)
{
   var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
   var customer = Customer.Get(customerId);
   var serializedCustomer = serializer.Serialize(customer);
   return JavaScript(
      "function getCustomer() { return (" + serializedCustomer + "); }");
}

Comments

2

This question has long been answered (and accepted), but I wanted to pass along a response to a similar question that helped me. His answer takes advantage of MVC3/Razor syntax:

https://stackoverflow.com/a/7486214/249153:

In mvc3 with razor @Html.Raw(Json.Encode(object)) seems to do the trick.

1 Comment

That is just awesome! Without @Html.Raw, I received an error with 'unexpected token &". In my case, I just do 'var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));'. At the moment, I'm not sure if Encode would be required or if it do similar thing like SerializeObject but it works.

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.