programing

MVC 컨트롤러에서 Json 개체를 반환하여 표시하는 방법

mbctv 2023. 3. 12. 11:09
반응형

MVC 컨트롤러에서 Json 개체를 반환하여 표시하는 방법

컨트롤러에서 json 객체를 전달해야 하는 MVC 어플리케이션을 실행하고 있습니다.

var dictionary = listLocation.ToDictionary(x => x.label, x => x.value);
return Json(new { values = listLocation}, JsonRequestBehavior.AllowGet);

컨트롤러에서 사용하고 있는 위의 코드는 현재 뷰 페이지를 전개하면 브라우저에 다운로드 대화상자가 열리고 파일을 열면 필요한 형식으로 json 객체가 나타납니다.

이제 뷰 페이지도 되돌리고 뷰 페이지의 json 객체에 액세스하고 싶습니다.어떻게 그럴 수 있지?

할 때return Json(...)특히 MVC에 뷰를 사용하지 말고 시리얼화된 JSON 데이터를 처리하도록 지시합니다.브라우저는 이 데이터로 무엇을 해야 할지 모르기 때문에 다운로드 대화 상자를 엽니다.

대신 뷰를 반환하려면 다음 작업을 수행합니다.return View(...)보통 때처럼:

var dictionary = listLocation.ToDictionary(x => x.label, x => x.value);
return View(new { Values = listLocation });

그런 다음 데이터를 JSON으로 인코딩하고 JavaScript 변수에 할당합니다.

<script>
    var values = @Html.Raw(Json.Encode(Model.Values));
</script>

편집

여기 좀 더 완벽한 샘플이 있습니다.이 샘플은 충분한 콘텍스트를 가지고 있지 않기 때문에 컨트롤러가 있다고 가정합니다.Foo, 액션Bar및 뷰 모델FooBarModel또, 장소의 리스트는 하드 코드 됩니다.

컨트롤러 / FooController.cs

public class FooController : Controller
{
    public ActionResult Bar()
    {
        var locations = new[]
        {
            new SelectListItem { Value = "US", Text = "United States" },
            new SelectListItem { Value = "CA", Text = "Canada" },
            new SelectListItem { Value = "MX", Text = "Mexico" },
        };

        var model = new FooBarModel
        {
            Locations = locations,
        };

        return View(model);
    }
}

모델 / FooBarModel.cs

public class FooBarModel
{
    public IEnumerable<SelectListItem> Locations { get; set; }
}

뷰/Foo/Bar.cshtml

@model MyApp.Models.FooBarModel

<script>
    var locations = @Html.Raw(Json.Encode(Model.Locations));
</script>

에러 메시지를 보면, 호환성이 없는 타입이 혼재하고 있는 것 같습니다(즉,Ported_LI.Models.Locatio‌​n그리고.MyApp.Models.Location이 때문에, 컨트롤러의 액션측에서 송신된 타입이 뷰로부터 수신된 타입과 일치하고 있는 것을 확인합니다.특히 이 샘플의 경우,new FooBarModel컨트롤러 매치 중@model MyApp.Models.FooBarModel뷰에 표시됩니다.

AJAX를 사용하여 이 컨트롤러 액션을 호출할 수 있습니다.예를 들어 jQuery를 사용하는 경우 다음 방법을 사용할 수 있습니다.

<script type="text/javascript">
    $.ajax({
        url: '@Url.Action("NameOfYourAction")',
        type: 'GET',
        cache: false,
        success: function(result) {
            // you could use the result.values dictionary here
        }
    });
</script>
<script type="text/javascript">
jQuery(function () {
    var container = jQuery("\#content");
    jQuery(container)
     .kendoGrid({
         selectable: "single row",
         dataSource: new kendo.data.DataSource({
             transport: {
                 read: {
                     url: "@Url.Action("GetMsgDetails", "OutMessage")" + "?msgId=" + msgId,
                     dataType: "json",
                 },
             },
             batch: true,
         }),
         editable: "popup",
         columns: [
            { field: "Id", title: "Id", width: 250, hidden: true },
            { field: "Data", title: "Message Body", width: 100 },
           { field: "mobile", title: "Mobile Number", width: 100 },
         ]
     });
});

$.ajax({
    dataType: "json",
    type: "POST",
    url: "/Home/AutocompleteID",
    data: data,
    success: function (data) {
        $('#search').html('');
        $('#search').append(data[0].Scheme_Code);
        $('#search').append(data[0].Scheme_Name);
    }
});

언급URL : https://stackoverflow.com/questions/15196528/how-to-return-json-object-from-mvc-controller-to-view

반응형