Reputation: 7176
I'm having an issue with using AJAX in MVC3. The problem is as I'm debugging the project, I see that the controller is getting the appropriate values passed in, I see that the query is being generated properly and is returning the same result as I get when I test it in LINQPad. When the query returns an empty result set, I don't get any errors. However, when there is data in the result set I get an "Internal Server Error". It seems that the problem lies is passing the JSON result from the controller to the view.
I have the code below.
[HttpPost]
public ActionResult Load(int value1, int value2, int value3)
{
var db = new MyDataContext();
List<Foo> items = new List<Foo>();
items = db.Foos.Where(f => f.v1 == value1 && f.v2 == value2 && f.v3 == value3).Take(50).ToList();
var results = Json(items, JsonRequestBehavior.AllowGet);
return results;
}
function Load() {
var v1 = 3;
var v2 = 2;
var v3 = 1;
$.ajax({
type: 'POST',
dataType: 'json',
url: '/FooBar/Load',
data: { value1: v1, value2: v2, value3: v3 },
error: function (xhr, status, error) {
alert('Error loading: "' + error + '"');
},
success: function (jsonresults) {
}
});
}
If someone could take a second look I would greatly appreciate it.
Upvotes: 0
Views: 1627
Reputation: 2198
Try changing your action method to return a JsonResult instead of an ActionResult. It's the only thing I can see that you're doing wrong, as I am doing pretty much the same thing and it's working as intended, but my controller method return a JsonResult.
Also, check out this link as it may or may not be helpful. It saved my butt a couple days ago:
Upvotes: 1
Reputation: 31043
i think this should work
[HttpPost]
public ActionResult Load(int value1, int value2, int value3)
{
var db = new MyDataContext();
List<Foo> items = new List<Foo>();
items = db.Foos.Where(f => f.v1 == value1 && f.v2 == value2 && f.v3 == value3).Take(50).ToList();
return Json(items);
}
Upvotes: 1
Reputation: 2801
try returning a jsonresult instead http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonresult.aspx
Upvotes: 1