2017-04-12 54 views
1

數據我有後臺控制器正確顯示來自AJAX(ASP.NET MVC)

[HttpGet] 
    public ActionResult EmailsList() 
    { 
     var itemsEmail = db.InvitationMails 
      .Select(x=> new 
      { 
       Email = x.To.ToString(), 
       Name = x.Name.ToString(), 
      }) 
      .ToList(); 
     return Json(itemsEmail, JsonRequestBehavior.AllowGet); 
    } 

這個代碼這對AJAX調用代碼

<script> 
$('#save_quest').click(function() { 
    email_update(); 
}); 

function email_update() { 
    $.ajax({ 
     url: '@Url.Action("EmailsList", "Questions")', 
     contentType: 'application/json; charset=utf-8', 
     type: 'GET', 
     dataType: 'json', 
     processData: false, 
     success: function (result) { 
      var email = result; 
      // console.log(result[0].Name); 
      for (var i = 0; i <= email.length - 1; i++){ 
       var emailHTML = '<div style="margin-left: 25px; margin-top: 10px;>' + '<b style="margin-left: 10px;">' + result.Email + '<b>' + '<b style="margin-left: 20px;">' + result.Name + '</b>' + '</div>' 
       $(".email_list").append(emailHTML); 
      } 
     } 
    }); 
} 

代碼工作得很好,但我在視圖上有undefined

enter image description here

如何我需要修改我的代碼,以顯示正確的呢?

+0

不喜歡這個結果[I] .Email並導致[I],請將.Name –

+1

是。感謝的傢伙@BasantaMatia – Eugene

+0

很高興知道它解決了您的問題。您可以標記爲回答我的解決方案以幫助某人:) –

回答

2

我寫這篇文章,以幫助別人,如果他/她得到了同樣的問題,

因爲它是對象的數組,所以你需要添加[I]與你的結果你在for循環中。

for (var i = 0; i <= email.length - 1; i++) 
    { 
    var emailHTML = '<div style="margin-left: 25px; margin-top: 10px;>' + '<b style="margin-left: 10px;">' + result[i].Email + '<b>' + '<b style="margin-left: 20px;">' + result[i].Name + '</b>' + '</div>' 
    $(".email_list").append(emailHTML); 
    } 

乾杯:)

相關問題