3

I'm new to asp.net MVC4, please be patient.

I have a controller which returns ActionResult with a model. I can use this model through Razor but I'd like to use it in JavaScript. this what I've tried to do according to some answers on the internet:

@{
var property = Model;
}
var prop = @(property);
var data= @Html.Raw(Json.Encode(prop ));

But it's not working. What do I need to do in order to pass my model to JavaScript?

asked Oct 5, 2013 at 19:47
1

1 Answer 1

14

Just use

 <script>
 var data = @Html.Raw(Json.Encode(Model));
 </script>

Problem with Your Code

@{
var property = Model; 
}
var prop = @(property); //Here model is not properly encoded
var data= @Html.Raw(Json.Encode(prop )); //You are passing Javascript variable
answered Oct 5, 2013 at 19:49
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.