charlie_cat
charlie_cat

Reputation: 1850

$.getJSON returns array,help needed with $.each

i have this code in my view which is in a loop which gives me two rows for console.log

var jqxhr = $.getJSON("<%= Url.Action("GetTrainingModulePoints" , "Home") %>", function (data) {
      console.log(JSON.stringify(data));
   });
   <%: Html.GetQTip("training-module-id-" + module.TrainingModuleId , "With assesment"  , "training-module-id-" + module.TrainingModuleId , Zinc.Web.Extensions.QTipPosition.Bottom, true, "Module Points") %>

in my controller:

public JsonResult GetTrainingModulePoints()
{
  var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
  IEnumerable<DataModels.Training.UserTrainingPointsDataModel> modulePoints = ZincService.TrainingService.GetTrainingModulePoints(currentUser.UserId);
  return Json(new { result = modulePoints}, JsonRequestBehavior.AllowGet);
}

each console.log gives:

 LOG: {"result":[{"InteractionType":6,"Points":50,"Name":"China Incentive Program"},{"InteractionType":8,"Points":1,"Name":"China Incentive Program"},{"InteractionType":6,"Points":50,"Name":"India - Q2 Incentive "},{"InteractionType":8,"Points":100,"Name":"India - Q2 Incentive "},{"InteractionType":6,"Points":50,"Name":"China - Q2 Incentive"},{"InteractionType":8,"Points":3,"Name":"China - Q2 Incentive"}]} 

 LOG: {"result":[{"InteractionType":6,"Points":50,"Name":"China Incentive Program"},{"InteractionType":8,"Points":1,"Name":"China Incentive Program"},{"InteractionType":6,"Points":50,"Name":"India - Q2 Incentive "},{"InteractionType":8,"Points":100,"Name":"India - Q2 Incentive "},{"InteractionType":6,"Points":50,"Name":"China - Q2 Incentive"},{"InteractionType":8,"Points":3,"Name":"China - Q2 Incentive"}]} 

how can i get the interactiontype,name and points seperate?

public static MvcHtmlString GetQTip(this HtmlHelper htmlHelper, string propertyName, string message, string propertyNameOverride = "", QTipPosition position = QTipPosition.Right, bool includeEvents = true, string title = "")
{
  string qtipPosition = String.Empty;

  switch (position)
  {
    case QTipPosition.Right:
      qtipPosition = "my: 'left center', at: 'right center'";
      break;
    case QTipPosition.Left:
      qtipPosition = "my: 'right center', at: 'left center'";
      break;
    case QTipPosition.Top:
      qtipPosition = "my: 'top middle', at: 'bottom middle'";
      break;
    case QTipPosition.Bottom:
      qtipPosition = "my: 'bottom middle', at: 'top middle'";
      break;
  }

  if (!String.IsNullOrWhiteSpace(propertyNameOverride))
    propertyName = propertyNameOverride;

  if (String.IsNullOrWhiteSpace(title))
    title = htmlHelper.Resource(Resources.Global.Title.Information);

  StringBuilder sb = new StringBuilder();
  sb.Append(String.Concat("$('#", propertyName, "').removeData('qtip').qtip({content: {text:"));
  sb.Append(String.Concat("'", message, "', title: { text: '", title, "', button: false }}, position: { ", qtipPosition, " }"));
  if (includeEvents)
    sb.Append(", show: { event: 'focus mouseenter', solo: true, ready: false }, hide: 'blur'");
  sb.Append(", style: { classes: 'ui-tooltip-shadow ui-tooltip-yellow' } });");

  return new MvcHtmlString(sb.ToString());
  }
}

 public sealed class MvcHtmlString : HtmlString
 {

 }

Upvotes: 0

Views: 114

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

Simply use the $.each() function:

var url = '<%= Url.Action("GetTrainingModulePoints" , "Home") %>';
var jqxhr = $.getJSON(url, function (data) {
    $.each(data.result, function() {
        var interactionType = this.InteractionType;
        var name = this.Name;
        var points = this.Points;
        // do something with those variables ...
    });
});

Here we are looping over the data.result collection in which each element represents an object having InteractionType, Points and Name properties according to the log you have shown. The $.each will obviously be executed for each element of the result collection.


UPDATE:

After the small discussion we had in the comments section it seems that you are doing something fundamentally wrong here. You are attempting to pass to a server side helper values that you have retrieved on the client using AJAX. That's impossible nr it makes any sense.

So you should be binding on the server. You shouldn't be doing any AJAX requests at all. You should simply call your server side helper and pass it the required parameters:

<%: Html.GetQTip(
    "training-module-id-" + module.TrainingModuleId, 
    Model.Points, 
    "training-module-id-" + module.TrainingModuleId, 
    Zinc.Web.Extensions.QTipPosition.Bottom, 
    true, 
    "Module Points"
) %>

Now all you have to do is add this Points property to your view model:

public string Points { get; set; }

and inside the controller action that is rendering this view simply set this property. You would first query your data layer to retrieve an IEnumerable<UserTrainingPointsDataModel> and then perform some transformation on this array to convert it to a string that you want to be displayed:

MyViewModel model = ... get the view model from somewhere
var currentUser = ZincService.GetUserForId(CurrentUser.UserId);
var modulePoints = ZincService.TrainingService.GetTrainingModulePoints(currentUser.UserId);
model.Points = ... transform the original points collection to some string that you want to pass to the helper;
return View(model);

Remark: I don't know where you took this Html.GetQTip helper but looking at its source code I am horrified. This helper doesn't encode anything. Your site is vulnerable to XSS attacks. Never use any string concatenations to build up javascript and pass variables to functions.

Upvotes: 1

Related Questions