在从JsonResult MVC3 /剃刀动态显示表/列表数据? [英] Display a table/list data dynamically in MVC3/Razor from a JsonResult?

查看:69
本文介绍了在从JsonResult MVC3 /剃刀动态显示表/列表数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图页面,users.cshtml。我有一个JsonResult动作方法,jsongetusers()返回用户的JSON格式的列表。

I have a view page, users.cshtml. And I have a JsonResult action method, jsongetusers() that returns the list of users in json format.

在users.cshtml页面加载,我想获得用户的列表,建一个表并显示它。什么是用剃刀在ASP.Net MVC实现这一目标的最佳方式是什么?我是pretty新MVC3和剃刀。我最初的想法是通过JSON结果和循环使用javascript / jQuery的建一个表,并追加到DOM。但我猜必须有一个更好的方式来做到这一点?

On users.cshtml page load, I want to get the list of users, build a table and display it. What is the best way to implement this in ASP.Net MVC using Razor? I am pretty new to MVC3 and Razor. My initial thought was to loop through the json result and build a table using javascript/jquery and append it to the DOM. But I am guessing there must be a better way to do this?

感谢。

推荐答案

作为空军终于曼建议,第一,然后让只是一个视图中再次再次调用Ajax来获取JSON结果是在这种情况下没有必要的。即2呼叫到服务器。我想你可以直接返回用户的HTML表中的第一个电话。

As Mystere Man suggested, getting just a view first and then again making an ajax call again to get the json result is unnecessary in this case. that is 2 calls to the server. I think you can directly return an HTML table of Users in the first call.

我们将在此方式做到这一点。我们将有一个强类型的视图将返回用户浏览器的列表的标记而这一数据是由一个操作方法,我们会从我们的浏览器使用HTTP请求调用提供。

We will do this in this way. We will have a strongly typed view which will return the markup of list of users to the browser and this data is being supplied by an action method which we will invoke from our browser using an http request.

有一个视图模型为用户

public class UserViewModel
{
  public int UserID { set;get;}
  public string FirstName { set;get;}
   //add remaining properties as per your requirement

}

和在你的控制器有一个方法来获取用户的列表

and in your controller have a method to get a list of Users

public class UserController : Controller
{

   [HttpGet]
   public ActionResult List()
   {
     List<UserViewModel> objList=UserService.GetUsers();  // this method should returns list of  Users
     return View("users",objList)        
   }
}

假设UserService.GetUsers()方法将返回UserViewModel对象,重新$ P $的名单psents在你的数据源usres名单(表)

Assuming that UserService.GetUsers() method will return a List of UserViewModel object which represents the list of usres in your datasource (Tables)

和你users.cshtml(这是在查看/用户文件夹),

and in your users.cshtml ( which is under Views/User folder),

 @model List<UserViewModel>

 <table>

 @foreach(UserViewModel objUser in Model)
 {
   <tr>
      <td>@objUser.UserId.ToString()</td>
      <td>@objUser.FirstName</td>
   </tr>
 }
 </table>

所有设置,现在你可以访问诸如 YO​​URDOMAIN /用户/列表的网址,它会给你一个HTML表格的用户列表。

All Set now you can access the url like yourdomain/User/List and it will give you a list of users in an HTML table.

这篇关于在从JsonResult MVC3 /剃刀动态显示表/列表数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆