Mojtaba Mojtaba - 1 month ago 14
Javascript Question

display json in popup returning ActionResult

I have a custom controller in mvc and the ActionResult is:

[HttpPost]
public ActionResult Details([DataSourceRequest]DataSourceRequest command, int id)
{
//var userDetail = _CustomerDetail.GetAllCustomers();
var genericDetail = _GenericDetail.Table.Where(x => x.EntityId == id).Select(z => new { z.Key, z.Value }).ToList().AsQueryable();
//var userData = from ud in userDetail
// join gd in genericDetail
// on ud.Id equals gd.EntityId
// select new { gd.Key, gd.Value };
DataSourceResult result = genericDetail.ToDataSourceResult(command);

return Json(result, JsonRequestBehavior.AllowGet);


}


which is returned an object like this:

{"Data":[{"Key":"Gender","Value":"F"},{"Key":"FirstName","Value":"h"},{"Key":"LastName","Value":"h"},{"Key":"DateOfBirth","Value":"1914-05-03"}],"Total":4,"AggregateResults":null,"Errors":null}


and my ajax and bootstrap popup codes are:



$.ajax({
type: "POST",
url: "/UserDetails/Details",
data: { id: dataItem.Id },
success: function (result) {
$('#dvDetail').html(result);
$('#myModal').modal('show');

},
error:function(){
alert('fail');
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="myModalLabel">User Detail</h4>
</div>
<div class="modal-body">
<div id="dvDetail"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>





I want to display my json object returning in 2 columns which are Key and Value and try many solutions of
stackoverflow
but did not success.

can anybody help me?

Answer

You need to give that object a template to render the data as a two column table/div, etc.

You can define a template function like this:

userDetailTemplate = function(data){
  var renderRow = function(val){
    return "<tr>" + val + "</tr>";
  }
  var renderCol = function(val){
    return "<td>" + val + "</td>";
  }
  var renderContent = function(val){
    return "<table>" + content + "</table>";
  }
  var content = [];

  for(i=0; i<data.length; i++){
    var key = renderCol(data[i].Key);
    var val = renderCol(data[i].Value);
    content.push(renderRow(key+val)); 
  }
  return renderContent(content.join(''));
}

In the Ajax callback, you need to call this template function.

    success: function (result) {
      $('#dvDetail').html(userDetailTemplate(result.Data)); // or this should be result. You need to try either of these.
      $('#myModal').modal('show');      
    },