1

As going through the site i got how to access the model in javascript and how to loop it in javascript. i am using text tag to access the item in a model. when i use i am not able to add break.

        @foreach (var item in Model.ArrayDetails)
           {
               var checklower = false;
               var checkUpper = false;
               var loopentered = false;

               <text>
                if(@item.Id ==1)
               { 
                  if(@item.LowerBound <= obj.value)
                      {
                       loopentered=true;
                       checklower=true;
                     }

                  if(loopentered)
                  { 

                  alert(@item.UpperBound <= obj.value);
                     if(@item.UpperBound <= obj.value)
                        {
                     checkUpper = true;
                    }
                  }

               if(checkUpper && checklower)
               {
              ***// here i want to add break statement(if i add javascript wont work)***
               }
             }
              </text>
            }

Can some one suggest me how can solve this.

4

1 回答 1

7

不要写这个汤。JSON 将您的模型序列化为 javascript 变量并使用此 javascript 变量来编写您的 javascript 代码。现在你有一个可怕的服务器端和客户端代码混合。

这就是我在实践中的意思:

<script type="text/javascript">
    // Here we serialize the Model.ArrayDetails into a javascript array
    var items = @Html.Raw(Json.Encode(Model.ArrayDetails));

    // This here is PURE javascript, it could (AND IT SHOULD) go into
    // a separate javascript file containing this logic to which you could
    // simply pass the items variable
    for (var i = 0; i < items.length; i++) {
        var item = items[i];

        var checklower = false;
        var checkUpper = false;
        var loopentered = false;

        if (item.Id == 1) {

            if (item.LowerBound <= obj.value) {
                loopentered = true;
                checklower = true;
            }

            if (loopentered) { 
                alert(item.UpperBound <= obj.value);
                if(item.UpperBound <= obj.value) {
                    checkUpper = true;
                }
            }

            if (checkUpper && checklower) {
                break;
            }
        }
    }
</script>

将 javascript 移动到单独的文件后,您的视图将简单地变为:

<script type="text/javascript">
    // Here we serialize the Model.ArrayDetails into a javascript array
    var items = @Html.Raw(Json.Encode(Model.ArrayDetails));

    myFunctionDefinedIntoASeparateJavaScriptFile(items);
</script>
于 2013-07-05T15:14:08.663 回答