[英]How do we set the value of an HTML element using Jquery and ASP.NET MVC 4 complex model data
In one of my ASP.NET MVC 4 view, I am using a Model's data to set the values of different HTML elements. 在我的ASP.NET MVC 4视图之一中,我正在使用模型的数据来设置不同HTML元素的值。 I can use this model in the view to display the values such as:
我可以在视图中使用此模型来显示诸如以下的值:
<div>@Model.Category.Name</div> etc...
But one of the div tag <div id="DivTotalCost"></div>
needs to display the total cost of all the products in all the categories. 但是div标签
<div id="DivTotalCost"></div>
需要显示所有类别中所有产品的总成本。 So at the end of the view I have the following script code to set the value of this DivTotalCost tag. 因此,在视图末尾,我具有以下脚本代码来设置此DivTotalCost标记的值。 But the following code does not set this value.
但是以下代码未设置此值。 I have put an alert statement to test the value and the alert displays:
我放置了一个警报语句来测试该值,并且警报显示:
function(){
return total;
}
View: 视图:
@model MyMVC_app.Models.ProductDetails
<div>@Model.Category.Name</div> etc...
<div id="DivTotalCost"></div>
@section scripts{
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryui")
<script type="text/javascript">
$(document).ready(function () {
var TotalCost = function () {
@if(Model.ProductCategoryList != null)
{
var total = "";
foreach(var item in Model.ProductCategoryList)
{
foreach(var product in @item.products)
{
total += product.price;
}
}
}
return total;
}
alert(TotalCost);
$('#DivTotalCost').text(TotalCost);
});
</script>
}
Please help. 请帮忙。
Thanks..Nam 谢谢..Nam
First: The alert displays 第一:警报显示
function(){
return total;
}
because you're passing the function itself, no its result. 因为您要传递函数本身,没有结果。 Your alert (and the div text assignment)should use the function result, like this
您的警报(和div文本分配)应使用函数结果,如下所示
alert(TotalCost());
now, inside the function you're mixing razor and javascript, and both are different things and run in a different time each, so you should adjust your code like this (not tested, but you might get the idea) 现在,在函数内部您将razor和javascript混合在一起,两者都是不同的东西,并且分别在不同的时间运行,因此您应该像这样调整代码(未经测试,但您可能会明白)
$(document).ready(function () {
var TotalCost = function () {
@{
var total = 0;
if(Model.ProductCategoryList != null)
{
foreach(var item in Model.ProductCategoryList)
{
foreach(var product in @item.products)
{
total += product.price;
}
}
}
}//end of razor block
return @total;
}
});
You can also create a ViewModel and add that logic on it, just in case you're open to try a different approach 您还可以创建一个ViewModel并在其上添加该逻辑,以防万一您愿意尝试其他方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.