Dynamically assign index via javascript to Razor Model

Viewed 148

I need to dynamically assign the index of each razor model through javascript.

Here is the javascript

function ResetIndexModel() {
            var idx = 0;
            $('.page-name').each(function () {
                var text = $(this).text();
                text = text.replace('Model.DraftPages[#].Name', 'Model.DraftPages[' + idx + '].Name');
                $(this).text(text);
                idx++;
            });
        }

and this is my HTML

<li class="active tabPage"><label for="Name" class="page-name">Model.DraftPages[#].Name</label><span title="Edit Page Name" class="glyphicon glyphicon-pencil" style="font-size:10px;"></span>></li>

I have also tried this.

text = text.replace('Model.DraftPages[#].Name', '@('@')Model.DraftPages[' + idx + '].Name');

so I need to replace the '#' symbol using the iteration from the js function. With my current code, it will only display 'Model.DraftPages[0].Name' in the label.

My expectation is, it supposed to display the value of @Model.DraftPages[0].Name

Is there any way I can achieve this?

2 Answers

before any explanation consider this: 1- razor page will be render in server side, so when you getting html page and its been loaded, you will see replaced values for model passed to razor page and cant change index of razor model with js.

2- instead you can change model to an js object and do what ever you whant with it, for example:

    <script>
    //this is js
    var equalRazorListModel = [
    //this is razor
    @foreach(var item in Model.DraftPages){
        <text>
          name:'@item.Name',
        </text>
    }
];
    </script>

in above code i converted your draft List of names to javascipt array. i hope this gives you some idea.

What ever value you want to display in the label can be passed like this

$(elements[idx]).text('@Model.DraftPages[' + idx + '].Name');

function ResetIndexModel() {
  var elements = $('.page-name');
  for (let idx = 0; idx < elements.length; idx++) {
    $(elements[idx]).text('@Model.DraftPages[' + idx + '].Name');

  }
}
ResetIndexModel();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="active tabPage">
  <label for="Name" class="page-name">Model.DraftPages[#].Name</label>
  <span title="Edit Page Name" class="glyphicon glyphicon-pencil" style="font-size:10px;"></span>
</li>

Related