36

I am doing an MVC application where i need to pass json object from controller to view.

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

The above code i am using in my controller , now when i deploy the view page its opening a download dialog in my browser , when open the file it gives me json object as i needed format.

Now i want to return my view page also want to access the json object in the view page. how can i do that.

4

4 に答える 4

60

そうするときは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。さらに、場所のリストはハードコーディングされています。

Controllers / 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);
    }
}

Models / FooBarModel.cs

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

Views / 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します。

于 2013-03-04T08:50:48.010 に答える
5

AJAX を使用して、このコントローラー アクションを呼び出すことができます。たとえば、jQuery を使用している場合は、次の$.ajax()メソッドを使用できます。

<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>
于 2013-03-04T07:29:16.563 に答える
0
<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 },
         ]
     });
});

于 2015-09-17T02:36:55.087 に答える
-2
$.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);
    }
});
于 2014-03-28T06:50:03.680 に答える