简体   繁体   中英

How to use the JavaScript loop index in the ViewBag list string

I want to use the JavaScript index to get the value of the viewBag list. But I have a mistake in combining the two. Thanks for guiding me

<script>
    for (var i = 0; i < @(Enumerable.Count(ViewBag.paramProperty)); i++) {
        select: `@(ViewBag.paramProperty[ + "${i}" + ]);
        var element = document.querySelectorAll(`[value="${select}"]`);
        element[0].setAttribute("checked", "checked");
    }
</script>

Firstly,you need to make sure you JsonConvert.SerializeObject with ViewBag.paramProperty,for example:

ViewBag.paramProperty = JsonConvert.SerializeObject(new List<string> { "a", "b", "c" });

Then try to set a js variable with ViewBag.paramProperty:

var paramProperty = @Html.Raw(JsonConvert.DeserializeObject(ViewBag.paramProperty));

and you can use:

for (var i = 0; i < paramProperty.lenght; i++) {
        select: paramProperty[i];
        var element = document.querySelectorAll(`[value="${select}"]`);
        element[0].setAttribute("checked", "checked");
    }

If I understand your code, you are trying to use a server-side variable in client-side. You can try to declare a javascript variable "paramProperty" and set its value to the ViewBag.paramProperty and then iterate over it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM