views:

800

answers:

2

Hi Everyone,

I'm trying to return a record from LINQ2SQL as a JsonResult to update my view page via jquery ajax. I'll post my code below. When I follow it through the debugger my function in the controller is being called and it is returning a record. I think there might be something wrong with my Jquery to retrieve the JSONResult. Any ideas?

View:

<a href="#" onclick="getProject(<%=project.ID%>)"><img src="<%=project.ThumbPath%>" alt="<%=project.Title%>" /></a>

Controller:

   Function DisplayProjectAjax(ByVal id As Integer) As JsonResult
        Dim project = From p In db.Projects Where p.ID = id
        Return Json(project)
    End Function

Jquery:

<script type="text/javascript">
    function getProject(id) {
        $(document).ready(function() {
            $.getJSON("/Portfolio/DisplayProjectAjax/" + id,
          {},
          function(data) {
              $("#Title").Text(data.Title);
          });
        }); 
    }
+2  A: 

Try:

$("#Title").text(data.Title);

or

$("#Title").html(data.Title);

Notice the casing... Also, something like Firebug will be helpful. You can look in the Net and Console tab and see all your requests, as well as debug your Javascript pretty easily.

JD Conley
I tried both of the suggestions and it's still not updating. I also checked Firebug and the response is the proper JSON. The #Title element is an <h3>. Any other suggestions? Thanks for your help.
Jon
A: 

The result of your query is an IEnumerable which is probably serialized as an array of Project objects even though there is only one. My VB syntax is probably bad but select the First() of the objects chosen by the selection.

return JsonResult( person.First() );

You'll need @JD Conley's fix as well, I think.

tvanfosson
I'll give it a shot when I get home tonight. I did try return JsonResult(person.Single()) and that didn't work, I'll for sure give this a try though, thanks!
Jon
The First() did it! Thanks!
Jon