Jignesh Rajput
Jignesh Rajput

Reputation: 3558

How to create Class object in .cshtml page MVC3?

i have create class with function to return DataTable

 namespace Office365
 {
    public class Office365
    {
         public DataTable GetQAData()
           {
              return Datatable;
           }  
    }
 }

this function use in Controlller and render data using ViewBag.Content like this

In .cshtml

       @Html.Raw(ViewBag.QAData)  

In Controller Code :

   using Office365;
   Office365 con = new Office365();

   StringBuilder sb = new StringBuilder();

        DataTable dt = con.GetQAData();
        int i = 1;
        foreach (DataRow dr in dt.Rows)
        {
           sb.append("<div></div>")
        }

        ViewBag.QAData = sb.ToString();

but is this possible to call class object on .cshtml and render my DataTable into Div? I means directly write code in .cshtml

Upvotes: 0

Views: 9336

Answers (1)

Iridio
Iridio

Reputation: 9271

I would create a ViewModel with a collection of your rows. Then from the page I will cycle trough it and create the html. Something like this

 public calss DataViewModel
 {
    public IList<MyRow> Rows {get;set;}
 }

From controller

    var model = new DataViewModel()
    model.Rows = new List<MyRow>();
    DataTable dt = con.GetQAData();
    int i = 1;
    foreach (DataRow dr in dt.Rows)
    {
       var row = new MyRow();
       /* populate the the MyRow class */
       Rows.Add(row);
    }

From the view

    @foreach(var item in Model.Rows)
    {
       <div>@item.MyField</div>
    }

I hope you get the idea

Upvotes: 2

Related Questions