1

I'm completely new in .NET core world. I faced a problem with converting @foreach (var item in Model.Products) into JavaScript array holding JSON product object (id, name). I tried solutions found in Stack Overflow and in some blogs, but each of them ends up in from server status 500 to ignored assignment.

Wrong attempts:

var yourjavascriptArray = <%=new JavaScriptSerializer().Serialize(cSharpArrayName);%>;

var inData = @Html.Raw(Json.Encode(Model.Products));

Code that is used:

Controller:

public IActionResult Index(string searchkey)
{
  ... 
  return View(new Models.ProductSearcherModel() { SearchKey = searchkey, Products = prods 
});

Index.cshtml:

@foreach (var item in Model.Products)
{
   //how to assign Model.Products to js array?
}
1
  • 1
    Please edit your question to show your attempts. We don't want to waste your time and ours suggesting solutions you've already tried and found to be lacking. Commented Jun 3, 2020 at 12:39

2 Answers 2

1

how to assign Model.Products to js array?

You can try to use JsonHelper.Serialize Method, like below.

@section scripts{
    <script>
        var products = @Json.Serialize(Model.Products);
        console.log(products);
    </script>
}

Test Result

enter image description here

Besides, if you'd like to retrieve data and do operation on JavaScript client side, you could achieve it using ajax etc.

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

Comments

1

This feels like the wrong approach.

I would probably generally recommend a separate ajax call to a controller to retrieve the json. But without seeing the code that you have it's difficult to say more.

Comments

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.