0

im new to the MVC pattern and got a problem passing variables to JS from C#.

Im passing a List from the viewmodel to the view that im storing in a hidden variable:

<input type="hidden" id="myID" name="myID" value="@Model.myList">

Then when im trying to grab this variable in JS:

const myList = document.getElementById("myID").value;

But then I get a System.Collections.Generic.List that I cant do anything with. How can i make it so that I can reach this List in JS?

1 Answer 1

1

The default string representation of an object in .NET is the class name. You don't want a string, you want the actual object itself. In this case it sounds like what you're looking to do is JSON-encode the data. So you wouldn't need an <input> at all, you can do that directly in the JavaScript code in your view:

const myList = @Html.Raw(Json.Encode(Model.myList));

This would result in myList in your JavaScript being the array of objects from the myList property on your server-side model.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your respone. I get an error message saying: 'IJsonHelper' does not contain a definition for 'Encode' and no extension method 'Encode' accepting a first argument of type 'IJsonHelper' could be found (are you missing a using directive or an assembly reference?)
@ziBBit: Hmm... It could change drastically depending on MVC version. This question seems to offer some suggestions for other MVC versions. Same concept, just different place to call it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.