[英]Html syntax not recognized inside If condition of Razor MVC
Below is the code i am using for one of my mvc views, within the mentioned if condition, html code is not recognized. 下面是我用于我的一个mvc视图的代码,在上述if条件下,无法识别html代码。
<table class="table">
<tr class="row h4">
<td>Task</td>
<td>Parameter</td>
<td>Active</td>
<td><input type="button" class="btn btn-default" value="Add Mapping" /></td>
</tr>
@foreach (OrderTypeTaskParameterMapping mapping in Model.OrderTypeTaskParameterMappings)
{
<tr class="row">
<td>
<select class="form-control">
@foreach (Task task in Model.Tasks)
{
<option value="@task.Id"
@if (mapping.TaskId == task.Id)
{
selected="selected" **doesn't work**
}
>@task.Name</option>
}
</select>
</td>
<td>
<select class="form-control">
@foreach (Parameter p in Model.Parameters)
{
<option>@p.Name</option>
}
</select>
</td>
<td>
@if (mapping.Active)
{
<input type="button" class="btn btn-info" value="Active" />
}
else
{
<input type="button" class="btn btn-danger" value="InActive" />
}
</td>
<td><input type="button" class="btn btn-info" value="Save" /></td>
</tr>
}
</table>
On executing the above code i get an error : 在执行上述代码时,我得到一个错误:
What could be the reason? 可能是什么原因? I thought this should have worked.
我认为这应该有效。 Am i missing something here?
我在这里想念什么吗?
Try this code 试试这个代码
<option value="@task.Id" @(mapping.TaskId == task.Id ? "selected" : string.Empty)>
Inside {} you can use only C# code 在{}内部,您只能使用C#代码
I think it also works using conditional attributes: 我认为使用条件属性也可以:
<option value="@task.Id" selected="@(mapping.TaskId == task.Id)">
If the expression evaluates to false
, then Razor will not output the selected
attribute. 如果表达式的计算结果为
false
,则Razor将不会输出selected
属性。
More on conditional attributes 有关条件属性的更多信息
About the original question, I believe the problem is related to how Razor tells HTML from C# blocks. 关于最初的问题,我相信问题与Razor如何从C#块告诉HTML有关。 On your code, you are not closing the
option
tag. 在代码上,您没有关闭
option
标签。 You're trying to open it, write (or not) the selected
attribute using a code block and then close it. 您试图打开它,使用代码块写入(或不写入)
selected
属性,然后将其关闭。
Inside the code block, Razor's expecting a line of code or a new HTML tag. 在代码块内部,Razor期望一行代码或一个新的HTML标签。 As it's not an HTML tag (no angle bracket) it tries to interpret it as C#, hence the
missing ;
由于它不是HTML标记(没有尖括号),因此会尝试将其解释为C#,因此
missing ;
message. 信息。
That's why the <tr>
and <td>
tags inside the parent @foreach(){}}
are working: because they can be interpreted as new HTML blocks. 这就是父
@foreach(){}}
中的<tr>
和<td>
标记起作用的原因:因为它们可以解释为新的HTML块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.