0

I have tried it like that but the JS function doesn't invoke

initial:

@{   
    List<CmsSite.Models.Category> category_list = (List<CmsSite.Models.Category>)ViewData["categories_details"];
}

pass to js function:

<button onclick="InsertNewProduct(@Json.Encode(category_list))">Save</button>

js function:

function InsertNewProduct(arr) {

    json_obj = {
                   //what to do here
    }

now arr is an array of JSON objects

I can't see the List<CmsSite.Models.Category> category_list values

How should I decode this on JS?

2 Answers 2

1

You can do this in following way:

@Json.Encode(category_list)

Upd:

<script>
    function testFunc(arr) {
        for (var i = 0; i < arr.length; i++) {
            alert(arr[i]);
        }
    }
</script>

<button onclick="testFunc(@Json.Encode(new List<string> { "1", "2", "3" }))">
    Save
</button>

If this don't work for you there may be problems with your model class (CmsSite.Models.Category) serialization.

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

3 Comments

Had no idea MVC just came with this. Good stuff.
i have edit the quastion, now i am getting an aray of objects
I tried this with List and this works just fine. See updated answer.
0

The client won't see category_list because that's server-side code and isn't delivered. You could use JavaScriptSerializer to serialize the list into JSON and output that to a Javascript variable, or hidden field to reference with JavaScript.

The following should output the thing, just find a place to put it:

@Html.Raw(new JavaScriptSerializer().Serialize(category_list))

So, if you do this in a script block that will be rendered on the client, assign the output of that call to a variable and then it's present when the page is loaded.

1 Comment

i have edit the quastion, now i am getting an aray of objects

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.