Let’s say you send a model called “MyModel” from controller to view.
In Controller:
... var result = new MyModel() { Id = 1, Name = "Ercan", FavoriteTeam = "Galatasaray", FavoriteGame = "Half Life Series" } return View(result); ...
and now we will send this model which comes with result to Javascript via setName function:
@{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); } <div class="row"> <h2 id="name">Name</h2> <button class="btn btn-primary" onclick="setName(@serializer.Serialize(Model))">Set Name</button> </div>
Finally access model as JSON format in JavaScript:
function setName(jsonData) { document.getElementById("name").innerHTML = jsonData.Name; document.getElementById("favoriteTeam").innerHTML = jsonData.FavoriteTeam; document.getElementById("favoriteGame").innerHTML = jsonData.FavoriteGame; }
Thanks solutionspirit.com