how to return JSON with MVC Controller

后端 未结 2 1657
小蘑菇
小蘑菇 2021-02-08 09:42

I am calling my controller method using .ajax. my controller method call web service which returns dictionary. now i need to return this and populate dropdown list. i am trying

相关标签:
2条回答
  • 2021-02-08 10:13

    In controller

        public JsonResult LookupValue(String sLookupIds)
        {
    
            SelectList olist = new SelectList(oDict, "key","value");
    
            return Json(olist);
    
      }
    

    In view

            $.ajax(
                {
                    url: 'LookupValue/',
                    data: { 'sLookupIds': selectedtext },
                    datatype: "json",
                    traditional: true,
                    success: function (data) {
                        $.each(data, function (index, val) {
                            $('#lookup')
                            .append($("<option></option>")
                            .attr("value", val.Value)
                            .text(val.Text));
                            //ddHTML = ddHTML + "<option  value='" + val.Value + "'>'" + val.Texts + "'</option>";
                        });
                    }
                });
    
    0 讨论(0)
  • 2021-02-08 10:14

    In your Action in your Controller:

    return Json(data);
    

    Where data is your object that you want serialiazed to JSON.

    If you want to use Json.NET, just override the Json method.

    0 讨论(0)
提交回复
热议问题