2014-01-17 13 views
0

我有JsonResult一個問題,因爲我是新來的JSON和MVC,所以,我從控制器傳遞JsonResult查看:我應該如何鍵入投我JSONResult到IEnumerable的

控制器:

public ActionResult Index() 
{ 
    return View(Json(_studentService.GetAllStudents(), JsonRequestBehavior.AllowGet)); 
} 

查看:

@model IEnumerable<StudentApp.Models.Student> 
@{ 
    Layout = null; 
} 

<!DOCTYPE html> 

<html> 
    <head> 
     <meta name="viewport" content="width=device-width" /> 
     <title>Index</title> 
    </head> 
    <body> 
      <fieldset> 
       <legend>Student</legend> 
       <div class="display-label"> 
        @Html.DisplayNameFor(model => model.name) 
       </div> 
       <div class="display-field"> 
        @Html.DisplayFor(model => model.name) 
       </div> 
      </fieldset> 
      <p> 
       @Html.ActionLink("Edit", "Edit", new { id=Model.id }) | 
       @Html.ActionLink("Back to List", "Index") 
      </p> 
     </body> 
</html> 

,但鑑於我收到異常。

+0

爲什麼不ü剛剛返回查看(_studentService.GetAllStudents()); –

+0

我成功地刪除了異常,但現在我得到了**'System.Collections.Generic.IEnumerable '沒有包含'name'的定義,也沒有擴展方法'name'接受可以找到類型'System.Collections.Generic.IEnumerable '的第一個參數(是否缺少使用指令或程序集引用?)** – HarshSharma

+0

如果傳遞Ienumerable,則表示嘗試使用@ Html.DisplayNameFor(model => model [0] .name)等等 –

回答

1

通行證只

public ActionResult Index() 
{ 
    return View(_studentService.GetAllStudents()); 
} 

鑑於使用

@foreach (var item in Model) 
{ 
    <tr> 
     <td> 
     @Html.DisplayNameFor(modelItem => item.Name) 
     </td> 
     <td> 
     @Html.DisplayFor(modelItem => item.Name) 
     </td> 
    </tr> 
} 
+0

是的,它的工作:),但我只是想知道,如果我不得不使用前面的場景,意思是如果我想用JSON函數返回結果,那麼我必須請問,請您告訴.. – HarshSharma

+0

Json數據將返回給ajax成功調用。 –

+0

這是什麼意思?請詳細說明我是新來json – HarshSharma