0

I have a list in the view called Model which I want to replace with a new list when the box is checked, using jquery. What is the easiest way to do this?

$(function () {
    $('input[type=checkbox]').change(function () {
        if (this.checked) {
            $.post("/Authentication/GetPeopleThatHaveOwnTransportation", {}, function (PeopleList) {
                //What do I write to replace this list (PeopleList) with the Model
            });
        }
    });
});
<div class="row">
    <div class="list">
    @foreach (var c in Model)
    {
        <div class="col-sm-4 col-lg-4 col-md-4">
            <div class="card hovercard">
                <div class="cardheader"></div>
                <div class="avatar">
                    <img alt="" src="/Uploads/@c.Picture">
                </div>
                <div class="info">
                    <div class="title">
                        <a target="_blank" href="http://localhost:53008/authentication/profileperson?id=@c.id">@c.FirstName @c.LastName</a>
                    </div>
                    <div class="desc">Age: @c.Age</div>
                    <div class="desc">Date Joined: @c.DateJoined</div>
                </div>
            </div>
        </div>
    }
    </div>
</div>
Mohammad
  • 21,175
  • 15
  • 55
  • 84
N. Sch
  • 667
  • 2
  • 5
  • 15

2 Answers2

0

You should write something like this:

$('.list').empty();
$('.list').html(PeopleList);

To make this work, you need to send your model to a partial view, render it, and return that rendered string as json.

This question and answers may guide you to the right path: Render Partial View Using jQuery in ASP.NET MVC

Community
  • 1
  • 1
Burak Karakuş
  • 1,368
  • 5
  • 20
  • 43
0

The following should overwrite the contents of the ".list" div (which was populated by the model on load) with the return results of your AJAX query:

$(function () {
    $('input[type=checkbox]').change(
     function () {
         if (this.checked) {
             $.post("/Authentication/GetPeopleThatHaveOwnTransportation", {}, function (PeopleList) {
                $(".list").html(PeopleList);
             });
         }
     });
});

Instead of passing back the model explicitly in your "GetPeopleThatHaveOwnTransportation" action, you could pass back a string of HTML that creates a list, just like you did in your view via razor.

Jason Graham
  • 904
  • 6
  • 12