0

Tried reading other similar questions but can't quite detect what's wrong with mine. I'm attempting to build an ajax call as follows:

$.ajax({
    type: "POST",
    url: '@Url.Action("Search", "Map")', // Map Controller, Search Action
    data: JSON.stringify({ "Location": x }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        var table = "<table class='table'>";
        $.each(data, function (index, value) { // For each element in data:
            table += "<tr><td>" + value.title + "</td></tr>"; // add it to the table list
            var latlng = new google.maps.LatLng(value.latitude, value.longitude);
            var marker = new google.maps.Marker({
                position: latlng,
                map: map
            });

            gmarkers.push(marker);
        });
        table += "</table>";
        $("#myData").html(table);
    }
});

It's supposed to send the text acquired from:

$("#txtSearch").keyup(function () {
    var x = $("#txtSearch").val();

Now the text is acquired correctly, therefore 'x' does have a value when it's submitted. But once the ajax request above is processed the method being called which is the Search Action under the MapController is called with a null parameter:

[HttpPost]
public ActionResult Search (string title)
{
    Entities mapEntity = new Entities();
    string userId = User.Identity.GetUserId();
    var result = mapEntity.Markers.Where(x => x.title.StartsWith(title) && x.UserId == userId).ToList();
    return Json(result, JsonRequestBehavior.AllowGet);
}

As long as the title remains null I can't really do anything with it... Appreciate any help on resolving this issue.

2 Answers 2

3

You are looking for the "Location" parameter not for "title" in search method.

data: JSON.stringify({ "Location": x })

please change the parameter name from "title" to "Location" then check.

Sign up to request clarification or add additional context in comments.

4 Comments

Don't you mean change from location to title?
either you change in search method or can in ajax call method. both results you the same. can prefer @darin dimitrov's answer also.
That's true yes but your answer was correct. It's just that your last sentence got the parameters the wrong way around
Thanks for the answer, that solved the initial problem, but the error is that even though the result I'm returning has a count of 1, the browser is catching a 500 (Internal Server Error) on it. I'm wondering if my success info has been specified correctly or not...
2

Try replacing those 2 parameters of your AJAX request:

data: JSON.stringify({ "Location": x }),
contentType: "application/json; charset=utf-8",

with this simple expression:

data: { title: x },

Notice that your action parameter is called title so that's what you should be sending.


UPDATE:

To resolve the 500 Internal Server error that you are getting, stop passing your domain entities to the views because they might contain circular references that cannot be JSON serialized. As always, use a view model to project your domain entities and include only the relevant information for the view:

var viewModel = result
    .Select(x => new 
    { 
        Prop1 = x.SimpleProp1, 
        Prop2 = x.SimpleProp2,
        Prop3 = x.NestedProp.Prop3,
    })
    .ToList();

return Json(viewModel, JsonRequestBehavior.AllowGet);

Btw, if you had inspected the AJAX request in the network tab of your browser, you would have seen that the response from your server is an YSOD in which the precise cause for the error is written.

Check it out so that you know how to debug those kind of problems next time (I have highlighted the important parts you should be looking at):

enter image description here

6 Comments

Your recommendation worked perfectly! But now the return to the action is working but it's not returning data correctly. It says 500 (Internal Server Error). I am returning that Json type of data, and running it through that $.each(data, function(index,value) { }); Any idea why that would be?
I can see you returning some domain Entity to the view instead if using a view model. Domain entities might contain circular references which obviously cannot be JSON serialized. That's why you are getting 500 Internal Server Error. To resolve this error stop passing domain entities to views and project the result to a view model.
Just like that: return Json(result.Select(x => new { Prop1 = x.Prop1, Prop2 = x.Prop2 }).ToList(), JsonRequestBehavior.AllowGet);. This way you will include only the information that's actually required by the view and will resolve the problem with circular object references that you currently have. I have updated my answer with this example.
Thanks for the reply mate, this is more than I could have asked for. It worked as you said (and never knew I could make viewModels on the fly like that without having a specially declared class for them under Models! One issue I have is that debugging thing you showed me, Going under network and selecting XHR, I don't have the Headers/Preview/Response tabs like you have, so I can't see that code. Other than that though, everything else worked as you promised! Thanks a lot, I can hopefully bring this assignment to a close! :)
Or not ... can the inverse hold true? I'm getting an internal server error as I'm trying to post the latitude and longitude back to the backend... Take a look at i.sstatic.net/ySyUw.png for an example. I tried stringifying it, using toString, sending as object, whatever I try the lngLat always results in internal server error. I don't get it x.x
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.