다음 C # 배열이 있으며 JavaScript로 전달하고 싶습니다. 그것을 달성하는 가장 좋은 방법은 무엇입니까? 감사합니다?
public static List<ListDetail> GetMyList()
{
List<ListDetail> myList = new List<ListDetail>();
myList.Add(new ListDetail() { Id = 1, Name = "Party" });
myList.Add(new ListDetail() { Id = 2, Name = "Course" });
myList.Add(new ListDetail() { Id = 3, Name = "Home" });
return myList.ToArray;
}
JsonConvert를 사용하여 객체를 JSON 문자열로 변환 할 수 있으므로 JavaScript로 쉽게 조작 할 수 있습니다.
// declare variable on your class
public string strJson;
...
// assign value in relevant method
strJson = Newtonsoft.Json.JsonConvert.SerializeObject(new myList);
그런 다음 프런트 엔드 웹 사이트에 문자열을 노출하기 만하면됩니다.
웹 양식을 사용 <%=strJson %>
하는 경우 <script>
태그 내부에 사용할 수 있습니다 . 또는 Literal을 사용할 수 있습니다.
예:
<script type="text/javascript">
var xyz = <%=strJson%>;
console.log(xyz);
</script>
또는 MVC를 사용하는 경우ViewData["Json"] = strJson;
컨트롤러 에서 사용한 다음 View @Html.Raw(ViewData["Json"])
의 <script>
태그 내부 에서 사용할 수 있습니다 .
예:
<script type="text/javascript">
var xyz = @Html.Raw(ViewData["Json"]);
console.log(xyz);
</script>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다