learning
learning

Reputation: 11735

simple question: Difficulty in declaring and using variable

What is wrong with the following code: I`m having the error message

Error 1 ; expected

    <%if (Model.ReferenceFields != null)
          {%>
            <%int count = 1; %>

            <%foreach (var referenceName in Model.ReferenceFields)
            {%>
             <%var value = "value"; %>
             <%count++; %>
             <%value = value + count.ToString(); %>
            <tr>
                <td><input type="hidden" name="Tests.Index" value='<%value%>' /></td>
                <td><input type="text" name="Tests['<%value%>'].Value"/></td>
                <td><input type="button" value= "Add" /></td></tr>
            <%}
               %>
         <%}
        %>

Upvotes: 3

Views: 55

Answers (1)

Ryan
Ryan

Reputation: 24482

The basic problem is lines like this

<input type="hidden" name="Tests.Index" value='<%value%>' />

So you're wanting to write out the contents of value into the html but thats not the way to do it. It should be

<input type="hidden" name="Tests.Index" value='<% Response.Write(value); %>' />

or a shortcut for Response.Write is <%= so

<input type="hidden" name="Tests.Index" value='<%= value %>' />

ASP101 - Writing Your First ASP.NET Page

The other problem is that the formatting of your code is, quite frankly butt ugly and you're making it hard work for yourself when trying to read it. Try this instead.

<%
if (Model.ReferenceFields != null)
{
    int count = 1; 
    foreach (var referenceName in Model.ReferenceFields)
    {
        var value = "value";
        count++;
        value = value + count.ToString(); 
        %>
        <tr>
        <td><input type="hidden" name="Tests.Index" value='<%= value %>' /></td>
        <td><input type="text" name="Tests['<%= value %>'].Value"/></td>
        <td><input type="button" value= "Add" /></td></tr>
        <%
    }
}
%>

Upvotes: 2

Related Questions