How to get Data from Model to JavaScript MVC 4?

asp.net, asp.net-mvc, asp.net-mvc-4, javascript

Solution

I think the best approach here is to use Json and something like Vue.js, Knockout.js, etc. (but also you can do it without these libraries, if your case is simple).

First, you need to install Json support with a command in PM console:

PM> install-package NewtonSoft.Json

Then, in your view you can convert your model to javascript object like this:

@model ...
@using Newtonsoft.Json

...

<script type="text/javascript">

    var data = @Html.Raw(JsonConvert.SerializeObject(this.Model));

</script>

Then you can access all the properties in your model with in plain JavaScript:

var id = data.CategoryID;

That's it! Use knockout (update 2018: this is obsolete, there is no reason you should use knockout now) if your logic is complicated and you want to make your view more powerful. It could be a little bit confusing for newbie, but when you get it, you'll gain the super-powerful knowledge and will be able to simplify your view code significantly.

Problem

that's my function: ``` <script> function Calculate() { var ItemPrice = document.getElementById("price"); var weight = document.getElementById("weight"); var SelWeight = weight.options[weight.selectedIndex].value; alert(SelWeight); var Category = document.getElementById("SelectedCategory"); var SelCategory = Category.options[Category.selectedIndex].value; alert(SelCategory); } </script> ``` i want to get `SelCategories.Tax` and `SelCategories.Duty` to add them to weight value and total price to show the total in a label.. I'm using ASP.NET MVC 4 and this is my Model that i want to use ``` public class CategoriesModel { public int CategoryID { get; set; } public string CategoryName { get; set; } public decimal Duty { get; set; } public decimal Tax { get; set; } public IEnumerable<SelectListItem> CategoriesList { get; set; } } ```

Original source

Related problems