Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return JSON with MVC Controller

Tags:

asp.net-mvc

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 with return JSON and need to populate using success (response)

I am using MVC 1.0

        $.ajax(
            {
                url: 'LookupValue/',
                data: { 'sLookupIds': selectedtext },
                datatype: "json",
                traditional: true,
                success: function (data) {
                    alert(data.value);
                }
            });

thanks in advance.

like image 877
jvm Avatar asked Feb 10 '12 04:02

jvm


People also ask

How can I get JSON result in MVC?

Right click on Home folder inside the View folder in the created MVC application as in the following screenshot: Give the name EmpDetails and click Add button. To bind view using json we need JQuery and the following JQuery library to communicate to the controller from view: <script src="~/Scripts/jquery-1.10.

What is return JSON in MVC?

JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Object Notation (JSON) format.

How do I return JSON data to view?

The Controller Action method will be called using jQuery POST function and JSON data will be returned back to the View using JsonResult class object. Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.


1 Answers

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>";
                    });
                }
            });
like image 172
jvm Avatar answered Oct 06 '22 00:10

jvm