Samuel Silva
Samuel Silva

Reputation: 43

Display SQL table with Umbraco MVC

I need to deliver something today and I am really stuck.

My goal is to show data from a table in Umbraco MVC (I am new to it)

Do I need to create a controller? Because All I did was create a Document type in Umbraco with a Template.

This is what I have in my Model:

public class RechargeModel
{
    public string Name { get; set; }
    public string Username { get; set; }
    public string Email { get; set; }
}

This is on my template:

@using Repower.Cms.Umbraco.Models;
@using Umbraco.Core.Persistence;
@{
using (var ipDb = new Database("UmbracoCMS"))
   {
      RechargeModel recharge;

      recharge = ipDb.Fetch<RechargeModel>(new Sql().Select("TOP 100").From("umbracoUsers"));
   }
}

I am getting an error saying that he cant convert type List to RechargeModel.

This is my HTML which I want to place on my page but I don't if I need to place it also inside the template or not or where to put it:

@model IEnumerable<Repower.Cms.Umbraco.Models.RechargeModel>

<table class="table table-hover">
    <thead>
        <tr>
            <td>User Name</td>
            <td>User Login</td>
            <td>User Email</td>
        </tr>
    </thead>
    <tbody>
        @{
            foreach (var item in Model)
            {
                <tr>
                    <td>@item.Name</td>
                    <td>@item.Username</td>
                    <td>@item.Email</td>
                </tr>
            }
        }
    </tbody>
</table>

Could someone please help? Also what about the rest of the code?

Thanks in advance!

Upvotes: 0

Views: 695

Answers (1)

harvzor
harvzor

Reputation: 2908

You can access the current database using ApplicationContext.Current.DatabaseContext.Database rather than newing up a Database object.

The issue is that .Fetch() returns an List (array) of RechargeModel, where as you are trying to assign this list to a single RechargeModel.

Either use:

var database = ApplicationContext.Current.DatabaseContext.Database;

var recharges = database.Fetch<RechargeModel>(new Sql().Select("TOP 100").From("umbracoUsers"));

Or change your variable so it accepts a List:

var database = ApplicationContext.Current.DatabaseContext.Database;

List<RechargeModel> recharges = null;

recharges = database.Fetch<RechargeModel>(new Sql().Select("TOP 100").From("umbracoUsers"));

Either way, you can then iterate over this list in your view:

@foreach (var recharge in recharges )
{
    <tr>
        <td>@recharge.Name</td>
        <td>@recharge.Username</td>
        <td>@recharge.Email</td>
    </tr>
}

Upvotes: 1

Related Questions