Home > database >  Pass javascript array to C# code Razor pages
Pass javascript array to C# code Razor pages

Time:08-12

I have the following JavaScript code in Index.cshtml

 function getActivity()
    {
        var collection = document.getElementsByClassName("skill-icon-selected");
        const splitCollection = new Array;
        for (var i = 0; i < collection.length; i  )
        {
            var split = collection[i].id.split("-");
            splitCollection.push(split[0]);
        }
        console.log(splitCollection);
        

    }

I want to pass the array splitCollection to Index.cshtml.cs to use

        public List<Activity> allActivities = new List<Activity>();

        public void OnGet()
        {
            allActivities = _context.Activities.ToList();
            foreach (var activity in allActivities)
            {
                if (splitCollection.contains(activity.Skill))
                {
                    //Do stuff
                }
            }

How would I access splitCollection in my cshtml.cs or the data in splitCollection to be usesd in c#

CodePudding user response:

Since you want to pass an array to cshtml.cs in razor page,you need to use Post method.So you can pass data to OnPost handler,here is a demo:

cshtml:

@Html.AntiForgeryToken()
@section Scripts{ 
<script>
    function getActivity() {
       var collection = document.getElementsByClassName("skill-icon-selected");
        const splitCollection = new Array;
        for (var i = 0; i < collection.length; i  )
        {
            var split = collection[i].id.split("-");
            splitCollection.push(split[0]);
        }
        console.log(splitCollection);
        $.ajax({
            type: "POST",
            url: "",
            data: JSON.stringify(splitCollection),
            headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
            contentType: "application/json",
            success: function (data) {

            }
        });
        console.log(splitCollection);


    }
</script>
}

cshtml.cs:

public void OnPost([FromBody] List<Activity> myAllActivities) 
        { 
            ...
        }
  • Related