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); }); }); }
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.
You’ll need @JD Conley’s fix as well, I think.