简体   繁体   中英

Refreshing a Partialview inside a DIV with jquery and Ajax

This is my partial view:

@model UADDPortal.ViewModels.DatabaseInfoViewModel

<table class="table table-bordered table-striped">
<tr>
    <td><h5> Status:  @Model.CurrentStatus </h5> </td>
    <td><input type="submit" class="btn btn-success" name="RefreshResourceStatus@(Model.CheckoutID)" id="RefreshResourceStatus@(Model.CheckoutID)" value="Refresh" /></td>
</tr>

This is my Main page:

<div id="ResourceStatus@(item.CheckoutID)"> 
  @Html.Partial("ResourceStatus", item)
</div>
<script type="text/javascript">
$(document).ready(function () {
    $('#RefreshResourceStatus@(item.CheckoutID)').click(function (e) {
        e.preventDefault();  // stop the links default behavior
        $('#ResourceStatus@(item.CheckoutID)').load('/Home/GetCurrentStatus/@(item.CheckoutID)');
    });
});
</script>

And finally, this is my ajax method inside my main MVC controller:

    #region ajax calls
    public PartialViewResult GetCurrentStatus(string Id)
    {
        var viewModel = new DatabaseInfoViewModel(null);
        viewModel.CheckoutID = Convert.ToInt32(Id);
        viewModel.CurrentStatus = viewModel.GetCurrentStatus(Convert.ToInt32(Id));

        return PartialView("ResourceStatus", viewModel);
    }

    #endregion ajax calls

The problem is that the refresh button generated in the DIV section, seems to work randomly...sometimes works...most of the time doesn't do anything....I cant figure out why....

If you have more than one item, better use data-* attribute for checkoutid population.

@model UADDPortal.ViewModels.DatabaseInfoViewModel

<table class="table table-bordered table-striped">
<tr>
    <td><h5> Status:  @Model.CurrentStatus </h5> </td>
    <td><input type="submit" class="btn btn-success btn-checkout" 
         data-chekout-id="@(Model.CheckoutID)" value="Refresh" /></td>
</tr>

Then

$(document).ready(function () {

    $('.btn-checkout').click(function(e){

      var checkoutId=$(this).data("chekout-id");
      var targetDiv='#ResourceStatus'+checkoutId;

      $.post('url',{Id:checkoutId},function(result){

        $(targetDiv).html(result);

       });
    });
});

As mentioned by Fede in the comments on his question

 $.ajaxSetup({ cache: false });

solved the issue for me.

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