这是我的职能:
<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>
我想获取 SelCategories.Tax
和 SelCategories.Duty
将它们添加到重量值和总价中以在标签中显示总价。我正在使用ASP.NET MVC 4,这是我要使用的模型
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; }
}
最佳答案
我认为这里最好的方法是使用 Json 和类似 Vue.js 的东西, Knockout.js等(但如果您的情况很简单,您也可以在没有这些库的情况下完成)。
首先,您需要在 PM 控制台中使用命令安装 Json 支持:
PM> install-package NewtonSoft.Json
然后,在您的 View 中,您可以像这样将模型转换为 javascript 对象:
@model ...
@using Newtonsoft.Json
...
<script type="text/javascript">
var data = @Html.Raw(JsonConvert.SerializeObject(this.Model));
</script>
然后您可以使用纯 JavaScript 访问模型中的所有属性:
var id = data.CategoryID;
就是这样!如果你的逻辑很复杂并且你想让你的 View 更强大,请使用 knockout(2018 年更新:这已经过时,没有理由你现在应该使用 knockout)。对于新手来说,这可能有点令人困惑,但是当您掌握它时,您将获得 super 强大的知识,并且能够显着简化您的 View 代码。
关于javascript - 如何从模型获取数据到 JavaScript MVC 4?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20471511/