如何创建一个全局剃刀变量来保持数组中的长度计数

时间:2016-02-09 18:06:45

标签: c# jquery asp.net-mvc razor

如何在剃刀中创建一个全局变量来跟踪SuccessCriteria的数量?我在点击SuccessCriteria按钮时动态创建insert-success-criteria的表单输入,并删除单击remove-success-criteria按钮时创建的最后一个。因此,我需要像model => model.SuccessCriteria[count]这样的东西,count在添加输入时递增,在删除输入时递减。

我在我的函数上方尝试了@{int count = 1; },但是它在本地存储它,我无法在我的函数中访问它

此外,有什么方法可以在删除数组时将其设置为null? 我试过@{SuccessCriteria[count] = null;},但这不起作用。

型号:

    public int SuccessCriteriaId { get; set; }
    [Required]
    [Display(Name = "Success Criteria/ROI:")]
    public virtual List<String> SuccessCriteria { get; set; }

查看:

<table>
<tr class="form-group col-xs-12">
    <td class="form-label col-xs-4">
        @Html.LabelFor(model => model.SuccessCriteria, htmlAttributes: new { @class = "control-label col-xs-12" })
    </td>
    <td class="form-input col-xs-8">
        <ul>
            <li class="base-success-criteria">
                @Html.EditorFor(model => model.SuccessCriteria[0], new { htmlAttributes = new { @class = "form-control col-xs-12" } })
                @Html.ValidationMessageFor(model => model.SuccessCriteria, "", new { @class = "text-danger" })
            </li>
       </ul>
   </td>
</tr>
<tr class="form-group col-xs-12">
    <td class="form-label col-xs-4"></td>
        <td class="form-input col-xs-8">
            <button class="btn btn-primary btn-xs" id="insert-success-criteria"><i class="glyphicon glyphicon-triangle-bottom"></i></button> Insert another measurement
         </td>
 </tr>
 </table>

脚本:

<script type="text/javascript">
@{int counter = ViewBag.SucCritCounter; }
jQuery(function ($) {
    $('#insert-success-criteria').on("click", function (e) {
        $(this).closest('tr').prev('tr').find('.remove-success-criteria').remove();
        $(this).closest('tr').prev('tr').find('ul')
            .append(
                '<li>' +
                '@Html.EditorFor(model => model.SuccessCriteria[counter], new { htmlAttributes = new { @class = "form-control col-xs-12" } })' +
                '<button class="btn btn-danger btn-xs remove-success-criteria"><i class="glyphicon glyphicon-remove"></i></button>' +
                '</li>');
            @{counter++; }
    });
});

jQuery(function($) {
    $('ul').on("click", "button.remove-success-criteria", function(e) {
        if (!$(this).closest('li').prev('li').hasClass('base-success-criteria')) {
            $(this).closest('li').prev('li')
                .append('<button class="btn btn-danger btn-xs remove-success-criteria"><i class="glyphicon glyphicon-remove"></i></button>');
        }
             @{counter--; }
        $(this).parent().remove();
    });
});

</sript>

1 个答案:

答案 0 :(得分:0)

Web.config

添加密钥
<appSettings>
    <add key="MY_GLOBAL_VALUE" value="1" />
</appSettings>

以这种方式获得

System.Configuration.ConfigurationManager.AppSettings["MY_GLOBAL_VALUE"];