How to serialize each item in IEnumerable for ajax post

Posted by bflemi3 on Stack Overflow See other posts from Stack Overflow or by bflemi3
Published on 2012-10-28T04:22:38Z Indexed on 2012/10/28 5:01 UTC
Read the original article Hit count: 172

Filed under:
|

I have a PartialView that displays IEnumerable<Movie>.

_MoviePartial.cshtml

@foreach(var movie in Model) {
    <div class="content">
        <span class="image"><img src="@movie.Posters.Profile" alt="@movie.Title"/></span>
        <span class="title">@movie.Title</span>
        <div class="score`">
            <span class="critics-score">@movie.Ratings.CriticsScore</span>
            <span class="audience-score">@movie.Ratings.AudienceScore</span>
        </div>
        @Html.ActionLink("Add Movie", "Add", "MyMovies")
    </div>
}

When the user clicks the "Add Movie" ActionLink I am going to do an ajax post to add the selected movie to the users collection. My problem is that I would like to send the entire selected Movie class to the "Add" action but not sure how to serialize each movie since the entire Movie class is not rendered in the PartialView, just a few properties. I know I can serialize something like this...

<script type="text/javascript">
    var obj = @Html.Raw(Json.Encode(movie));
</script>

But I'm not sure how that would work inside a foreach loop that renders html, especially inside a PartialView.

So, just to be clear, when a user clicks the "Add Movie" ActionLink I would like to send the serialized Movie class for that respective movie to my controller via ajax.

My questions is...

Is there a better way to serialize each movie and append it to it's respective anchor? I know there's the data- html5 attribute but I thought they only allow string values, not json objects. I also know I could use jQuery's .data() function but I'm struggling to think through how to get that to run from a PartialView, especially since the html rendered by _MoviePartial.cshtml may be returned from a controller via ajax.

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about asp.net-mvc-4