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>
CodePudding user response:
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");
}
CodePudding user response:
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