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.
You can do this easily with the KoGrid plugin for KnockoutJS.
Sample
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
and in your controller have a method to get a list of Users
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),
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.The normal way of doing it is:
You don't need a JsonResult or jQuery for this.
If you really need to go this way, then this is what you can do. There are probably better ways of doing it, but this is all that I have at the moment. I did no database calls, I just used dummy data. Please modify the code to fit in with your scenario. I used
jQuery
to populate theHTML table
.In my controller I have the an action method called
GetEmployees
that returns aJSON result
with all the employees. This is where you would call your repository to return the users from a database:The User class looks like this:
In your view you could have the following:
Regarding the code above:
var url = '/Home/GetEmployees';
Home
is the controller andGetEmployees
is the action method that you defined above.I hope this helps.
UPDATE:
This is how I would have done it..
I always create a view model class for a view. In this case I would have called it something like
UserListViewModel
:In my controller I would populate this Users list from a call to the database returning all the users:
And in my view I would have the following:
Add a View:
Add a controller and action method to call the view: