How can I create a global variable in razor that keeps track of the count of SuccessCriteria
? I am dynamically creating form inputs for SuccessCriteria
when the insert-success-criteria
button is clicked and removing the last one created when the remove-success-criteria
button is clicked. As a result I need something like model => model.SuccessCriteria[count]
with count
being incremented when an input is added and decremented when an input is removed.
I tried @{int count = 1; }
above my functions but this stores it locally and I cannot access it within my function
Also, is there a way to set the element of an array to null when I remove it?
I tried @{SuccessCriteria[count] = null;}
however that does not work.
Model:
public int SuccessCriteriaId { get; set; }
[Required]
[Display(Name = "Success Criteria/ROI:")]
public virtual List<String> SuccessCriteria { get; set; }
View:
<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:
<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>