当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - mvc ajax refresh div method controller json

问题描述:

I have a method in the controller that return a ViewBag with Json.

 public JsonResult FilterCheck(int id, int[] mycheck, string idprot)

{

ViewBag.Utenti = this.GetDbContext().utente.Include(s => s.cod_servizio_utente).Where(x => x.cod_servizio_utente.Select(l => l.id).Contains(5)).ToList();

return Json(ViewBag.Utenti, JsonRequestBehavior.AllowGet);

}

In the view I have this script function ajax, if this function have "success" i would refresh a div that include a foreach on the viebag.Utenti:

 $.ajax({

type: "POST",

url: "@Url.Action("FilterCheck","Operatore")",

datatype: "json",

traditional: true,

data: { 'mycheck': mycheck, 'idprot': idprot, 'id': '@Model.id' },

success: function(data) {

var html = $(data).filter('#external-events').html();

$('#external-events').html(data);

}

});

<div id='external-events'>

@foreach (HAnnoZero.Repositories.utente item in ViewBag.Utenti)

{

<div class='col-lg-3'><div class='external-event'>@item.id- @item.cognome @item.nome</div></div>

} </div>

But dont work. How can do for refresh the foreach inside div id "external events"?Who could help me?

网友答案:

Firstly you do not need to assign the collection to ViewBag

public ActionResult FilterCheck(int id, int[] mycheck, string idprot)
{
  var data = this.GetDbContext().utente.Include(......
  // Build anonymous object collection to avoid circular reference errors
  var response = data.Select(d => new
  {
    id = d.id,
    cognome = d.cognome
    // other properties as required
  });
  return Json(response);
}

Secondly you are returning JSON, not html, so in your success function you need to iterate through the properties and build your html (not sure what your properties are, so adjust as necessary)

success: function(data) {
  $('#external-events').empty(); // clear existing items
  $.each(data, function(index, item) {
    var div = $('<div><div>'); // Create new element
    div.text(item.id + ' ' + item.cognome); // Set inner text
    $('#external-events').append(div); // add the new element
  });
}

An alternative is to have the action method return a partial view containing the html and then use

success: function(data) {
  $('#external-events').html(data);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: