我有一些有效的Razor语法代码在视图中,可以成功地构建和运行。然而,在Visual Studio 2012中,代码无法正确格式化,Razor似乎在解析此文档时很“脆弱”,当我使用CTRL + K + D自动格式化代码时,一些内容向左浮动,难看,不能按嵌套的父子结构进行格式化。我无法在第二个if条件中添加@
,这可能会修复向左浮动的HTML内容。
@foreach (var customField in Model.CustomFields)
{
<tr>
<td>
@customField.label
</td>
<td>
<div class="col-md-4 padding-0">
@switch (customField.custom_field_type_id)
{
case Constants.CustomFieldType.checkbox:
foreach (var opt in customField.custom_field_options.Select((x, i) => new { Data = x, Index = i }))
{
var optValue = customField.custom_field_values.FirstOrDefault(item => item.custom_field_option_id == opt.Data.custom_field_option_id && item.custom_field_id == customField.custom_field_id);
<div class="checkbox">
<label>@opt.Data.custom_field_option_value</label>
@if (optValue != null)
{
var optName = customField.custom_field_id + "_" + opt.Data.custom_field_option_id + "_" + optValue.custom_field_value_id;
<input type="checkbox" id="CustomFieldEdit_@opt.Data.custom_field_option_id" name="CustomFieldEdit_@optName" @(optValue.value.ToLower() == "true" ? "checked" : "") />
<input type="hidden" id="CustomFieldOrig_@opt.Data.custom_field_option_id" name="CustomFieldOrig_@optName" value="@optValue.value" />
}
else
{
var optName = customField.custom_field_id + "_" + opt.Data.custom_field_option_id + "_0";
<input type="checkbox" id="CustomFieldEdit_@(opt.Data.custom_field_option_id)" name="CustomFieldEdit_@optName" @(opt.Data.is_checked ? "checked" : "") />
}
</div>
}
break;
case Constants.CustomFieldType.text_input:
var textinputVal = customField.custom_field_values.FirstOrDefault();
if (textinputVal != null)
{
var textInputName = customField.custom_field_id + "_0_" + textinputVal.custom_field_value_id;
<input type="text" id="CustomFieldEdit_@(customField.custom_field_id)" name="CustomFieldEdit_@(textInputName)" value="@textinputVal.value" class="form-control" />
<input type="hidden" id="CustomFieldOrig_@(customField.custom_field_id)" name="CustomFieldOrig_@(textInputName)" value="@textinputVal.value" class="form-control" />
}
else
{
var textInputName = customField.custom_field_id + "_0_0";
<input type="text" id="CustomFieldEdit_@(customField.custom_field_id)" name="CustomFieldEdit_@(textInputName)" class="form-control" />
}
break;
}
</div>
</td>
</tr>
查看 Visual Studio 2012 Professional 格式化我的视图代码的屏幕截图:
<text>
标签包装内容。Razor 处理它作为内容而不是代码。 - UtopiaLtdtextInputName
等变量实际上没有被使用。要确保任何涉及将文本直接连接到经Razor处理的值(例如CustomFieldEdit_@customField.custom_field_id
)的内容都需要进行Razor部分转义。否则,邮件接收者是在customField.custom_field_id域名下的CustomFieldEdit_。 - UtopiaLtd