2

这是来源:

<% string[] roles = ViewData["Roles"] as string[]; 
                   if (roles != null && roles.Length > 0) {%>
            <p>
                <label for="roleName">
                    Role:</label>
                <% foreach (string role in roles) { %>
                <%: Html.RadioButtonFor(m => m.RoleName, role) %>&nbsp; <span>
                    <%: role%></span>
                <% } %>
            </p>
            <%} %>

这是我的尝试:

 @{
        string[] roles = ViewData["Roles"] as string[]; 
        if (roles != null && roles.Length > 0) {
            <p>
                <label for="roleName">Role:</label>
                foreach (string role in roles) {    
                    @Html.RadioButtonFor(m => m.RoleName, @role)&nbsp; <span>@role</span>
                    }
            </p>
        }
    }

问题是在运行时我收到以下错误消息:

Compiler Error Message: CS0103: The name 'role' does not exist in the current context

Source Error:

Line 41:                 <label for="roleName">Role:</label>
Line 42:                 foreach (string role in roles) {    
Line 43:                     @Html.RadioButtonFor(m => m.RoleName, @role)&nbsp; <span>@role</span>
Line 44:             </p>
Line 45:         }

有人可以看看有什么问题。我试过了,但我的尝试似乎有问题。到目前为止,我还尝试将第 43 行更改为:

@Html.RadioButtonFor(m => m.RoleName, role)&nbsp; <span>@(role)</span>

@Html.RadioButtonFor(m => m.RoleName, role)&nbsp; <span>@role</span>

两者仍然不起作用:-(

4

3 回答 3

0
foreach (string role in roles) {    
    @Html.RadioButtonFor(m => m.RoleName, @role)&nbsp; <span>@role</span>
}

应该

@foreach (string role in roles) {    
    @Html.RadioButtonFor(m => m.RoleName, role) <span>@role</span>
}
于 2012-05-17T14:10:58.730 回答
0
@Html.RadioButtonFor(m => m.RoleName, @role)&nbsp; <span

应该

@Html.RadioButtonFor(m => m.RoleName, role)&nbsp; 

@role 是正确的。但 RadioButtonFor(...) 调用中不需要 @ 符号

于 2012-05-17T14:08:02.713 回答
0

尝试这个:

@{
    string[] roles = ViewData["Roles"] as string[]; 
    if (roles != null && roles.Length > 0) {
    <p>
        <label for="roleName">Role:</label>
        @foreach (string role in roles) {    
            @Html.RadioButtonFor(m => m.RoleName, @role)@:&nbsp;<span>@role</span>
        }
    </p>
    }
}

或者您可以使用:

@{
    string[] roles = ViewData["Roles"] as string[]; 
}
@if (roles != null && roles.Length > 0) {
<p>
    <label for="roleName">Role:</label>
    @foreach (string role in roles) {    
        @Html.RadioButtonFor(m => m.RoleName, @role)@:&nbsp;<span>@role</span>
    }
</p>
}
于 2012-05-17T14:19:41.017 回答