Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing ASP.NET MVC model data from with Javascript

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.

like image 577
Fermin Avatar asked Dec 08 '25 08:12

Fermin


1 Answers

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>
like image 83
Richard Avatar answered Dec 10 '25 07:12

Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!