views:

33

answers:

1

Hi, I have a beginner level Json question with MVC.net (I've never really used jquery or json) so please excuse me if I ask something stupid.

I have a javascript file with the below

<script>
    function refreshMovies() {
        //$.getJSON("/Home/Refresh", showMovies);
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/Home/Refresh",
            success: showMovies
        });
    }

    function showMovies(movie) {
        var frag = "<ul>";
        frag += "<li>" + movie[0] + " - " + movie[1] + "</li>";
        frag += "</ul>";         
        alert(frag);
        $("#divMovies").html(frag);
    }
</script>

My Home controller looks like:

public ActionResult Refresh()
{            
        return Json(GetMovies());   // Method Returns IList<Movies>
}

The question I have is the frag on the alert and when the UL is displayed on the page is always empty.

However, firebug does show that the post request is returning the json, so maybe something is going wrong with showMovies()?

A: 

You say that firebug reports that you are getting your JSon correctly, otherwise I'd ask you whether you decorated the action with [HttpPost], as you are using the POST method.

Does the alert() currently display the correct HTML? If so, does the div have the id="divMovies" attribute (note, no # character here!).

Otherwise, try to move the alert() on top of the showMovies: does it show anything?

Palantir
I might be wrong but the action only needs to be decorated if I want to restrict the method to certain html actions, so it should still work.The alert basically just shows "<ul></ul>"the divMovies div looks like: <div id="divMovies"> </div>
N00b
ok, try to alert() the returned json (alert(movie)) and see what it prints...
Palantir
[object Object]Firebug jSon is like: {"Movie":{"Title":"The something","Director":"john smith"}}
N00b
that seems a single Movie object, which you should be able to access as movie.Title and movie.Director (instead of movie[0] and movie[1])
Palantir
Ok I have change it to movie.Title movie.Director and now the alert before the $("#divMovies").html(frag); is showing <ul> undefined undefined </ul>
N00b
I can't test it right now, but you are on the right way. How about movie.Movie.Title? :)
Palantir
arh yes, movie.Movie.Title worked perfectly, could you please explain why movie.Title didn't work though? I wouldve thought the Json object Movie would be assigned to movie? and thus movie.Title shouldve worked.
N00b