Using MVC Model in javascript

Using MVC Model in javascript

Added by Nasir Mahmood updated on Friday, November 7, 2014


Previously while working on Mapping project, I need to pass model of razor view to javascript function because function parameters change any time, there is a solution to pass parameters individually but handling these parameters is another issue more over situation is more worst when number of parameters grows up. So I decided to find a way to pass whole model as a parameter to javascript function.


Following is dummy model which we use in our example.

public class Person
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }

Now populate values in this model in controller and pass model to view.

Encode Model:

Now the tricky part is using Json.Encode helper function which encode our model as json object. Following in code

<a href='#' onclick="Getinfo('@Json.Encode(Model)')" >Click Here </a>				

Calling in Javascript:

Now we have got Model object but before using it we have to convert it back json object,By following code we can use our object in javascript.

function showmap( info ) {
    var obj = JSON.parse( info );

That's it!


32 Tutorials
27 Snippets
6 Products


Contact Us

Contact us

Stay Connected