MVC 4 and jQuery getJSON

2019-08-08 02:54发布

问题:

I have to implement some sort of live search in a project at the university. I have the following code: MVC Action:

[Authorize]  
[AcceptVerbs(HttpVerbs.Get)]  
[InitializeSimpleMembership]
public JsonResult Search(string term)  
{  
    var data = ... // get matching item  
    return Json(data, JsonRequestBehavior.AllowGet);  
}  

Script in View:

$(document).ready(function() {  
    $("#searchText").keyup(function() {  
        $.getJSON('/Search/Search', { "term": $(this).val() },  function(result) {   
            alert(result);    
            $("#searchText").val(result.d);  
        });  
    });  
});

The controller action is called and returns the matching objects, but the javascript function is never called, no alert box, nothing. What can do to make this work?

回答1:

There could be a problem with the JSON serialization of your data. This could often happen if you are attempting to directly serialize your EF domain models which might contain circular references, ... The correct approach is of course to use view models.

In order to track the problem use FireBug and look at the Network tab to see the exact request/response of the AJAX call. There you will be able to see the response returned by the server which will contain the error message.