ChumpStick ChumpStick - 6 months ago 15
JSON Question

MVC 4 ajax query not accepting json object from controller

.aspx page:

<script type="text/javascript">
$(document).ready(function ()
{
$('********').click(function (id)
{
var test = "test";
$.ajax(
{
type: "POST",
url: "*************",
data: { type: test },
dataType: "string",
success: function (data) { show(data); },
failure: function () { alert("Failed"); }
});
});
});

function show(data)
{
alert("Worked");
}
</script>


Controller function:

[HttpPost]
public ActionResult getTest(String type)
{
List<Test> test = new List<Test>();
SqlConnection con = new SqlConnection("*****************");
SqlCommand cmd = new SqlCommand("****************");
cmd.Connection = con;
cmd.Connection.Open();
SqlDataReader reader = cmd.ExecuteReader();

int i = 0;
while (reader.Read())
{
test.Add(new Test{ itemName = reader.GetString(0),
itemType = reader.GetString(1),
itemClass = reader.GetString(2),
imageURL = reader.GetString(3)});
}
var test = Json(test, JsonRequestBehavior.AllowGet);
return test;
}


I changed names of stuff around in the code, but anyways when I run the website and click on the div it contacts the controller and returns the correct json object(put breakpoint in at the return line to verify what test was filled with). Nothing is ever returned to the webpage though. In the web browser debugger I put a breakpoint in the ajax function and that hits, but when I hit continue it never hits the breakpoint I put in the show function. Also it does not show the alert("error") either and when I take the data out or change the url it will show the error alert.

Things I have tried...

Changing the controller type to JsonResult - controller returns same thing, but never gets back to the page.

Tried adding a contentType to the ajax function - causes the controller to never get even get called. No matter what value I put in. "application/json; charset=utf-8" <- this one does not work.

Tried the shorthand version of ajax where you just put success: show.

Answer

I figured it out... I changed the return type of the controller function to String and then use the JavaScript serializer to turn the list of models I had created into a JSON string that could be passed back to the ajax function on the view. Also I removed the dataType in the ajax function, since ajax is able to auto figure out what the return type is mostly.

JavaScript:

<script type="text/javascript">
        $(document).ready(function () 
        {
            $('********').click(function (id) 
            {
                var test = "test";
                $.ajax(
                {
                    type: "POST",
                    url: "*************",
                    data: { type: test },               
                    success: function (data) { show(data); },
                    failure: function () { alert("Failed"); }
                });
            });
        });

        function show(data)
        {
            alert("Worked");
        }
</script>

Controller:

[HttpPost]
public String getTest(String type)
{
     List<Test> test = new List<Test>();
     SqlConnection con = new SqlConnection("*****************");
     SqlCommand cmd = new SqlCommand("****************");
     cmd.Connection = con;
     cmd.Connection.Open();
     SqlDataReader reader = cmd.ExecuteReader();

     int i = 0;
     while (reader.Read())
     {
          test.Add(new Test{ itemName = reader.GetString(0),
                             itemType = reader.GetString(1),
                             itemClass = reader.GetString(2),
                             imageURL = reader.GetString(3)});
     }
     System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new     System.Web.Script.Serialization.JavaScriptSerializer();
     var temp = jSearializer.Serialize(test);
     return temp;
}

This code returned a JSON object to the view that I could then use like an array of objects, so I could add multiple divs to my view for each object and then write the objects values to the divs as well.