1

asp.net mvc のコントローラーでクラスのオブジェクトを作成し、それをビュー モデルごとにビュー ページに渡します。

このオブジェクトには、さまざまなデータ型 ( xmldocumentstringintarrayなど) を返す多くのメソッドがあります。

次の方法を使用して、任意のメソッドにアクセスしました@Model.Getxml().ChildNodes.Count" "@Model.Getxml().ChildNodes[0].InnerText

このオブジェクトの変数をjavascriptで宣言し、次のように変数から必要なメソッドを呼び出したい

var obj=@Model

そして、obj変数から任意のメソッドにアクセスします

しかし、次のように配列内の要素をトレースするためのループを記述すると問題が発生します

var size=parseInt("@Model.Getxml().ChildNodes.Count");
for  (var i=0; i<size; i++) 
{
    document.writeln ("@Model.Getxml().ChildNodes[i].InnerText");
}

このコードは機能しませんでした。助けていただければ幸いです。

4

2 に答える 2

1

サーバー側のコード (c#) とクライアント側のコード (javascript) を混同しています

json または xml の値を変換して非表示フィールドに入れ、非表示フィールドの値を JavaScript 別名クライアント側の for ループで処理する必要があります。


サーバー側のコードを識別しやすくするため

@Model.Getxml().ChildNodes.Count特定のケースではJavascriptコードと@Model.Getxml.ChildNodes[i].InnerText組み合わせることができないサーバーコードです


クライアント側のコードを識別しやすくするため

var size=parseInt(<variable>);
for  (var i=0; i<=0; i++) 
{
    document.writeln ("<Text>");
}

現在、カウントの回数だけ印刷していると思います

@Model.Getxml.ChildNodes[i].InnerText
@Model.Getxml.ChildNodes[i].InnerText

于 2013-05-03T05:19:35.807 に答える
0

An alterntive to Harsh Baid's answer would be to create the loop in Razor, rather than in Javascript, i.e. 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.

于 2013-05-03T08:54:08.710 に答える