How to return Json object from MVC controller to view

前端 未结 4 684
我寻月下人不归
我寻月下人不归 2020-11-29 03:28

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         


        
相关标签:
4条回答
  • 2020-11-29 03:48

    You could use AJAX to call this controller action. For example if you are using jQuery you might use the $.ajax() method:

    <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>
    
    0 讨论(0)
  • 2020-11-29 04:01

    When you do return Json(...) you are specifically telling MVC not to use a view, and to serve serialized JSON data. Your browser opens a download dialog because it doesn't know what to do with this data.

    If you instead want to return a view, just do return View(...) like you normally would:

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

    Then in your view, simply encode your data as JSON and assign it to a JavaScript variable:

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

    EDIT

    Here is a bit more complete sample. Since I don't have enough context from you, this sample will assume a controller Foo, an action Bar, and a view model FooBarModel. Additionally, the list of locations is hardcoded:

    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>
    

    By the looks of your error message, it seems like you are mixing incompatible types (i.e. Ported_LI.Models.Locatio‌​n and MyApp.Models.Location) so, to recap, make sure the type sent from the controller action side match what is received from the view. For this sample in particular, new FooBarModel in the controller matches @model MyApp.Models.FooBarModel in the view.

    0 讨论(0)
  • 2020-11-29 04:08
    <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 },
             ]
         });
    });
    

    0 讨论(0)
  • 2020-11-29 04:11
    $.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);
        }
    });
    
    0 讨论(0)
提交回复
热议问题