tags:

views:

69

answers:

2

I'd like to to provide data to a table in the views. The data is not only from database but also from a csv file.

Should I store the data in the ViewData, or should I store it in a object and pass it to views? What is the best approach, or any other methods I can use? Thx!

A: 

You should create a model object, fill it in the controller with data from heterogeneous sources and pass that model to the view.

Mehrdad Afshari
thx, but how can I do that? I mean how to creat a model object?
Smallville
+1  A: 

Use strongly-typed views and pass the object directly to the view:

// Model (PersonRepository class)
public static Person Get(Int32 id) {
  using (MyContext context = new MyContext()) {
    Person p = context.Person.First(p => Person.id == id);
    return p;
  }
}

...

// Controller
public ActionResult Show(Int32 id) {
  return View(PersonsRepository.Get(id);
}

...

// View
<%@ Page Inherits="System.Web.Mvc.ViewPage<Models.Person>" Title="" Language="C#" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

  <%= Model.Id %> <br />
  <%= Model.Name %> <br />

</asp:Content>
aleemb
I can't see how you can do Person.Id and Person.Name. You probably mean Model.Id and Model.Name...
Mehrdad Afshari
Indeed, that was the intent. Fixed.
aleemb
I would suggest creating a PersonViewModel class which has a Person property.
Todd Smith