2017-03-28 1 views
-2

JSON에 C# 개체를 구문 분석하는 방법은 무엇입니까?C# 개체 목록을 JSON으로 변환

이 내가 가진 코드는 다음과 같습니다

모델 :

namespace MvcApplication1.Models 
{ 
    public class HolidayModel 
    { 
     public int HolidayID { get; set; } 
     public string HolidayDescription { get; set; } 
     public string HolidayStartDate { get; set; } 
     public string HolidayEndDate { get; set; } 
     public int Count { get; set; } 
     public string HolidayOld { get; set; } 
     public string HolidayNew { get; set; } 
     public int EmployeeID { get; set; } 
     public int HolidaySelectedYear { get; set; } 

     public int StartDay { get; set; } 
     public int StartMonth { get; set; } 
     public int StartYear { get; set; } 

     public int EndDay { get; set; } 
     public int EndMonth { get; set; } 
     public int EndYear { get; set; } 
    } 
} 

컨트롤러 :

public ActionResult GetEvents() 
{ 
    List<Holiday> holidays = conn.Holidays.ToList(); 

    ViewBag.holidaysJson = Json(holidays, JsonRequestBehavior.AllowGet); 
    return View(); 
} 

및보기

나는 다음 코드를 사용하여 경고 상자에 JSON을 인쇄하려고 :

<script> 
    alert("@ViewBag.holidaysJson"); 
</script> 

하지만 빈 경고 상자가 나타납니다.

여기에 문제가 있습니까?

+2

holidaysResult! =이 holidaysJson –

+0

난 그냥 그것을 변경하지만 난 여전히 빈 경고 상자 –

+1

이 Json'은 단순히 (A ['JsonResult' 인스턴스]를 반환'호출하지 않습니다 얻을 https://msdn.microsoft.com /en-us/library/system.web.mvc.jsonresult)? 이게 니가 원하는거야? –

답변

3

당신은 단지보고 다음 Json.Encode 방법을 사용하여 JSON으로 변환 다시 모델을 전달할 수 있습니다

컨트롤러 코드는 다음과 같습니다

public ActionResult GetEvents() 
{ 
    List<Holiday> holidays = conn.Holidays.ToList(); 
    return View(holidays); 
} 

및보기 :

@model List<Holiday> 
<script> 
    var holidaysJson = @Html.Raw(Json.Encode(Model)); // json object 
    alert(JSON.stringify(holidaysJson)); // converting it to string representation 
</script> 
0

jsonconvert.serializeobject 방법을 사용할 수 있습니다.

public ActionResult GetEvents() 
{ 
    List<Holiday> holidays = conn.Holidays.ToList(); 
    ViewBag.holidaysResult = JsonConvert.SerializeObject(holidays); 
    return View(holidays); 
}