Get value from Js and bind to a json data attribute in cshtml

440 views Asked by At

I have a requirement to get client side data in json and pass the json in a data attribute in cshtml. Then will read the values from the data attribute.

 <div class="container" data-attribute="{Json}">

This above json will contain the data from client side (collected using js).

Any suggestion on how to make this work.

  1. passing json in data attribute in cshtml
  2. reading the value from the attribute in cs file
1

There are 1 answers

0
Sumit Bhatia On

If you want to set the data attribute as Json and you mentioned that it is collected through JS, then you can use this JS code to set it to a div.

var data_str = encodeURIComponent(JSON.stringify(my_object));
$("div#mydiv").attr("data-hero",data-str);

And if you want to retrieve it then you can use this code.

var data_str = $("div#mydiv").attr("data-hero");
var my_object = JSON.parse(decodeURIComponent(data_str));

At one point, you mentioned that you want to read the attribute in the cs file, so I hope you are calling an Ajax request, where you can read the data from the attribute as given above and pass it into your POST request and you can read it in cs code.

Follow this article to pass Json using Ajax.

Send JSON data via POST (ajax) and receive json response from Controller (MVC)