nam
nam

Reputation: 23749

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. 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. So at the end of the view I have the following script code to set the value of this DivTotalCost tag. 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

Upvotes: 0

Views: 1385

Answers (1)

pollirrata
pollirrata

Reputation: 5286

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

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)

$(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

Upvotes: 1

Related Questions