Using MVC Model in javascript

Using MVC Model in javascript

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

Problem:

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.

Model:

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 );
    console.log(obj.ID);
    console.log(obj.Name);
    console.log(obj.Address);
    console.log(obj.Phone);
}
				

That's it!

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected