Iterating throgh mvc model lists using javascript
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 it开发者_开发技巧erate 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
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.');
}
}
精彩评论