Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

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

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?

Thanks.

like image 693
user471317 Avatar asked Mar 22 '12 02:03

user471317


1 Answers

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.

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.

Have a ViewModel for the User

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)        
   }
}

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

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>

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.

like image 126
Shyju Avatar answered Oct 26 '22 02:10

Shyju