I've created an object of class in controller in asp.net mvc and pass it to view page by view model,
This object has many methods that return different data type ( xmldocument
, string
, int
, array
, etc)
I've used the following way to access any methods @Model.Getxml().ChildNodes.Count" "@Model.Getxml().ChildNodes[0].InnerText
I want to declare a variable of this object in javascript and call any methods that I want from the variable like the following
var obj=@Model
And then access any methods from obj
variable
But I have a problem when I write loop for tracing elements in array like the following
var size=parseInt("@Model.Getxml().ChildNodes.Count");
for (var i=0; i<size; i++)
{
document.writeln ("@Model.Getxml().ChildNodes[i].InnerText");
}
This code didn't work, Help would be appreciated.
You are mixing up the server-side code (c#) and client-side code (javascript)
You should convert the values in json or xml and put in hidden field and process the value in the hidden field in for loop in javascript aka client-side..
To help you identify the server-side code
@Model.Getxml().ChildNodes.Count
and @Model.Getxml.ChildNodes[i].InnerText
are server code which cannot be combined in your particular case with Javascript code
To help you identify the client-side code
var size=parseInt(<variable>);
for (var i=0; i<=0; i++)
{
document.writeln ("<Text>");
}
Currently I suppose it would be printing as many times the count
@Model.Getxml.ChildNodes[i].InnerText
@Model.Getxml.ChildNodes[i].InnerText
An alterntive to Harsh Baid's answer would be to create the loop in Razor, rather than in Javascript, ie create a Razor loop to write out lines of JS, like so:
<script type="text/javascript">
@foreach(var node in Model.Getxml().ChildNodes)
{
@String.Format("document.writeln(\"{0}\");", node.InnerText)
}
</script>
This will output something like the following:
<script type="text/javascript>
document.writeln("Inner text 1!");
document.writeln("More inner text!");
document.writeln("etc.");
document.writeln("etc.");
document.writeln("etc.");
</script>
Here, the server-side code loops over these values as it's the only thing that has access to them. It then effectively writes out a bunch of lines of client-side code with hardcoded strings. It's not the most elegant solution, but it might help you to understand the difference.
This is in contrast to what you are currently trying to do, which is write out Javascript that will loop over these values, which it can't do, because these values no longer exist when Javascript does its thing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.