简体   繁体   中英

How can I easily append data from checkboxes in MVC?

I want to append HTML/data to div when the checkboxes is checked. I also want to know the best practices to how append data/html easily from the checkboxes.

However, please see the code below:

Ajax

 $('.myCheck').on('ifChecked', function (event) {
    $.ajax({
        url: '/Home/getCategoryItems',
        type: "GET",
        cache: false,
        data: {
            name: $(this).attr("name")
        },
        success: function (data) {
            setTimeout(function () {


            }, 3000);
        }
    });
});

View:

 @foreach (var item in Model.Cars)
  {
                <span class="label">
                    @item.CategoryName <span class="badge">@item.CategoryCount</span>
                </span>
                            @Html.CheckBox(item.CategoryName, new { @class = "myCheck", })
                            @Html.Hidden("name", item.CategoryName, new { id = item.CategoryId })
}




Controller:

    [HttpGet]
    public JsonResult getCategoryItems(string name)
    {
        var select = (from r in _db.Cars             
                      where r.Category.Name == name
                      select new
                      {
                          r.Title,
                          r.Price,
                          r.FileName,
                          r.Category.Name,
                          r.City,
                          r.TagName,
                          r.Id,
                          }).ToList();
        return new JsonResult { Data = select, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

This is what I want to append:

@foreach (var item in Model)
    {
        <div class="container" id="sek1">
            <div class="row">

                <div class="col-md-12 no-padding-lr sear-result-column">
                    <div class="latest-job article-row1">
                        <div class="col-md-2 no-padding-lr resp-grid1 box-sadow">
                            <img src="https://wp-themes.com/wp-content/themes/jobile/images/no-image.jpg" width="100" height="86">

                        </div>

                        <div class="col-md-10 no-padding-lr">
                            <div class="col-md-8 col-sm-8 col-xs-8 no-padding-lr job-status resp-grid1 job-status-3">

                                <h3>@item.Title</h3>
                            </div>
                            <div class="col-md-4 col-sm-4 col-xs-4 job-status resp-grid1 job-status-3">
                                <a class="btn btn-primary" id="LesMerBtn">@item.Price</a>
                            </div>
                            <div class="col-md-12 no-padding-lr">
                                <div class="job-btn-group late-job-btn clearfix">

                                    <a href="" rel="category" class="person-post"><span class="glyphicon glyphicon-map-marker"></span>@item.City</a>

                            <a href="" rel="category" class="person-post"><span class="glyphicon glyphicon-list-alt"></span>Kategori: @item.CategoryName</a>

                        </div>
                    </div>
                    <div class="col-md-12 no-padding-lr">
                        <p class="result-btm-text"></p><p>Test....</p>
                        <a href="" class="color-068587"><span class="glyphicon glyphicon-eye-open" id="eye-open"></span>Read more</a><p></p>

                    </div>
                </div>


            </div>
        </div>


    </div>
</div>

    }

You will get the json response in your success event of your ajax call. The response is of an array and you need to iterate through the array and get each item in the array, read the property values and use that to build your html markup you want to append.

success: function (data) {
   var myHtml="";
   $.each(data,function(a,b){
                               myHtml+="<div><p>"+b.Title+"</p>";
                               myHtml+="<p>"+b.City+"</p>";
                               myHtml+="<p>"+b.Price+"</p></div>";
   });
   $("#YourDivId").append(myHtml);
}

Assuming YourDivId is the Id of the Div where you want to show the data coming from your ajax call and this div exists in your page.

This works if you are making simple html markup. But if you have some complicated markup you want to appen/show. i recommend returning a partial view from your ajax call.

So in your action method, instead of returning the json data, pass that data to your partial view and let the action method returns the razor generated html markup with the data.

Assuming you have a view model like this to represent a Car

public class CarVm
{
  public string Title { set;get;}
  public decimal Amount { set;get;}
  public string City { set;get;}
}

In your action method, create a list of CarVm from the data from your db table and pass that to the partial view.

[HttpGet]
public JsonResult getCategoryItems(string name)
{
    var carVmList= (from r in _db.Cars             
                  where r.Category.Name == name
                  select new CarVm { Title =r.Title,
                                     City =r.City,
                                     Price=r.Price
                                   }
                 ).ToList();
    return PartiaView("CarsPerCategory",carVmList);
}

Assuming you have a partial view called CarsPerCategory.cshtml which is strongly typed to a collection of CarVm type. The partial view should exist in either ~/Views/Shared/ or ~/Views/YourCurrentControllerName/

@model List<CarVm>
@foreach (var item in Model)
{
  <p>@item.Title</p>
  <!-- Add the remaining markup you want (same as the code in your question) -->
}

And in your success event you simply append the response coming back to your container div.

success: function (data) {
  $("#YourDivId").append(data);
}

you may use append() method or html() method depending on you want to replace the existing value or just append it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM