views:

36

answers:

1

I want to iterate through my model values. Following is what I did to achieve this. But the varible count never increments. How can I increment it to iterate throgh my model values?

<script  language="javascript" type="text/javascript">
     function AddStudentName() {

                    var StudentName = document.getElementById('txtStudentName').value;

                    StudentName= StudentName.replace(/^\s+|\s+$/g, '');

                    if(StudentName!= null)
                    {                
                      <%int count = 0; %>
                      for(var counter = 0; parseInt(counter)< parseInt('<%=Model.StudentInfo.Count%>',10); counter++)
                      {
                        alert('<%=count%>');
                        if('<%=Model.StudentInfo[count].StudentName%>' == StudentName)
                        {
                          alert("A student with new student name already exists.");
                          return false;
                        }
                        <%count = count +1;%>
                      }
                    }
                }
    </script>

thanks, Kapil

+1  A: 

The code <%count = count + 1;%> will only execute once, on the server-side, when ASP.NET generates the HTML page. That is the reason why it will never increment. You cannot mix logic on server-side and client-side like that.

You can consider building an array in JavaScript filled with the data in Model.StudentInfo[i].StudentName, and then simply iterate through the JavaScript array:

var i;
var studentName = document.getElementById('txtStudentName').value;

// Prepare a 'StudentNamesString' in ASP.NET in the following format:
//
//    ['Student Name 1', 'Student Name 2', 'Student Name 3']
//
// And use it as follows:

var studentNamesOnServer = <%= StudentNamesString; %>;

studentName = studentName.replace(/^\s+|\s+$/g, '');

for (i = 0; i < studentNamesOnServer.length; i++) {
   if (studentNamesOnServer[i] === studentName) {
      alert('A student with new student name already exists.');
   }
}
Daniel Vassallo
DO i need to decorate the string items with single quotes?
kapil
Can i create the StudentNameString on view itself?
kapil
@kapil: Yes, you need to decorate the string items in quotes. However I'm not sure if you can create `StudentNameString` in the view. I'm not familiar with ASP.NET MVC. But if you can iterate through `Model.StudentInfo[i].StudentName` in the view, I guess you can.
Daniel Vassallo
Note that you can also use the following in JavaScript: `var studentNamesOnServer[]; studentNamesOnServer.push('Name 1'); studentNamesOnServer.push('Name 2'); ...`. This is instead of initializing the array in 1 line with `var studentNamesOnServer = <%= StudentNamesString; %>;`
Daniel Vassallo