首页 > 解决方案 > foreach 和 if 循环中变量的有效性

问题描述

我正在尝试将表单输入标签的自定义标题元素放在一起。

我需要将它插入到 foreach 循环中,这是我迄今为止尝试过的,但是title当我的变量放在我的label元素中时,不包含数据:

string title;
        foreach (var item in items)
        {
            var defaultCheckedString = Model.GetDefaultSelectedString(item);
            var checkedString = string.IsNullOrEmpty(defaultCheckedString) ? string.Empty : "checked";

            if (item.Caption == "extend")
            {
                title = "some custom text";
            }
    %>
    <div class="form-group">
        <label title="<%: title %>" class="control-label col-sm-10 roi-label"><%: item.Caption %></label>
            <div class="col-sm-2">
            <% if(Model.AllowMultiSelect) { %>
            <input type="checkbox" roilabel="<%: formElement.SourceContent.Name %>" name="<%: formElement.ElementName %>" value="<%: item.Value %>" class="form-control FormChoice__Input FormChoice__Input--Checkbox" <%: checkedString %> <%: defaultCheckedString %> data-f-datainput />
            <% } else  { %>
            <input type="radio" roiname="<%: formElement.SourceContent.Name %>" name="<%: formElement.ElementName %>" value="<%: item.Value %>" class="form-control FormChoice__Input FormChoice__Input--Radio" <%: checkedString %> <%: defaultCheckedString %> data-f-datainput />
            <% } %>

            </div>
    </div>

    <% } %>

更新 1:

在 Visual Studio 中,如果我将鼠标悬停在title已放置在label标记中的变量上,则会收到以下消息:

使用未分配的局部变量“title”

在此处输入图像描述

标签: c#

解决方案


推荐阅读