views:

214

answers:

1

Hi,

I am making an application usign MVC and LINQ.

I have a controller called home which does this:

    Dim notes = From x In dal.tbl_notes _
                Join y In dal.tbl_note_users On y.user_id Equals x.note_id _
                Select x.note, x.datestamp, y.is_owner, y.note_user_id
    ViewData("notes") = notes
    Return View()

And a page called home which has this code for displaying the output:

<%  For Each note In ViewData("notes")%>
    <%=Html.Encode(note.ToString)%>
<% next %>

However, the output looks like this:

{ note = vbnv, datestamp = , is_owner = True, note_user_id = 1 }

How can i output individual columns (like note or datestamp)? Is there a better way of doing this?

I have tried using viewdata.model but the data is from two different tables, so i can't say what type it is.

Thanks

+3  A: 

Create a ViewModel class that contains the note text, date, boolean isOwner, and the user id.

Public Class NoteViewModel
     public Note as String
     public DateStamp as DateTime
     public IsOwner as Boolean
     public NoteUserID as Integer
End Class

Select this using your the values from the join.

Dim notes = From x In dal.tbl_notes _
            Join y In dal.tbl_note_users On y.user_id Equals x.note_id _
            Select new NoteViewModel With { .Note = x.note, _
                                            .DateStamp = x.datestamp, _
                                            .Is Owner = y.is_owner, _
                                            .NoteUserId = y.note_user_id _
                                          }
Return View(notes)

Then have your view be strongly typed with the NoteViewModel. This will let you reference Model.Note, etc.

<%  For Each note In Model %>
    <%= Html.Encode(note.Note) %>
    <%= note.DateStamp.ToString("M/d/yyyy") %>
    <%= IIF( note.IsOwner, "yes" , "no") %>
    <input type='hidden' value='<%= note.NoteUserId %>' />
<% next %>
tvanfosson
Definitely the better way to go. Easier to add other model data to the page when the complexity increases.
Jason Miesionczek
Works almost perfectly, thanks!The only problem is the<%--<%= note.IsOwner ? "yes" : "no" %>--%>part. I get a compildation error when i try to use it.
Little bit of C# creeping in. Corrected.
tvanfosson
Thanks! Thought it looked a bit suspiscious ;)