Reputation: 51
.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.
Upvotes: 1
Views: 1428
Reputation: 89
I was struggling with a similar issue today: JSON object was always null.
var id = $('#ModalCategoryId').val();
var category = $.trim($('#ModalCategory').val());
var categoryJson = new Object();
categoryJson.CategoryId = id;
categoryJson.Category = category;
var data = JSON.stringify(categoryJson);
$.ajax({
"url": SAVE_CATEGORY_URL,
data: data,
type: "POST",
dataType: 'json',
traditional: true,
contentType: 'application/json; charset=utf-8',
and the controller action method declaration:
[HttpPost]
public ActionResult SaveCategory(CategoryLookupUIObject category)
the json would always show up as null UNTIL I changed the parameter name to something besides "category." Apparently having a Category property on my object and having the parameter also called category was blowing it up. As soon as I changed it to e.g:
[HttpPost]
public ActionResult SaveCategory(CategoryLookupUIObject categoryLookup)
it started passing a view model object instead of null. Any parameter name works, except "category".
I noticed the OP had a property called Type and also the name of his parameter on the controller was "type", so I felt compelled to point out that this was the source of the problem in my case; perhaps for the OP as well?
Good luck!
Upvotes: 0
Reputation: 51
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.
Upvotes: 1
Reputation: 106
Try this. "dataType" is what you send, "accepts" is what your query accepts.
$.ajax({
url: 'PUT_YOUR_URL_HERE',
dataType: "json",
accepts:"application/json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ Make: maka.value }),
async: true, // Or false
cache: false,
success: function (data) {
//do something
}
},
error: function (xhr) {
alert('error');
}
});
Upvotes: 0
Reputation: 696
You need add:
contentType: 'application/json; charset=utf-8',
Example:
$.ajax({
url: 'PUT_YOUR_URL_HERE',
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ Make: maka.value }),
async: true, // Or false
cache: false,
success: function (data) {
//do something
}
},
error: function (xhr) {
alert('error');
}
})
Upvotes: 0
Reputation: 1038710
Get rid of this line from your AJAX request:
dataType: "string",
Your controller returns JSON, so make sure that you specify the correct type:
dataType: "json",
But since jQuery is intelligent enough to use the Content-Type
response header to guess the correct content type you can simply remove it.
Also IIRC, the error function is called error
instead of failure
.
Upvotes: 0