开发者

MVC3. How to select additional column from joined table and send them all to View?

How to select addi开发者_如何学运维tional column from joined table and send them all to View as PagedList?

public ViewResult Index(...)
{
    var newlist = from n in db.students
                  join o in db.info on n.id equals o.id
    select n;
    //     ^ This only select collection from "students" as "n".

    return View(newlist.ToPagedList(..., ...));
                     // ^ using PagedList Extenstion
}

I want to join to some others tables and get some additional columns.

Any chance to use it in cshtml file (View) like this?:

@foreach (var item in Model) {
    <td>@item.column_from_students_table_1</td>
    <td>@item.column_from_students_table_2</td>
    <td>@item.column_from_info_table_1</td>
    <td>...</td>
}


You could create your own custom view type and select to that:

ViewModel:

public class StudenInfoView
{
    //From Students
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    //From info
    public int Age { get; set; }
}

Linq Query:

var newlist = (from n in db.students
               join o in db.info on n.id equals o.id
               select new StudenInfoView {
                   Id = n.Id,
                   FirstName = n.FirstName,
                   LastName = n.LastName,
                   Age = o.Age
               });


Since you are passing your Entity directly to your view that comes from some ORM provider (probably L2S or entity framework) so you can use properties both from student and info tables. You can perfectly fetch columns from student's table using

<td>@item.column_from_students_table_1</td>
<td>@item.column_from_students_table_2</td>

when it comes to fetching columns from info table, it depends upon relationship between two tables (if it is created in db). if student class (created by your mapper) has property of type EntitySet you can access columns from info table like

<td>@item.Infos.FirstOrDefault().Column_from_info_table</td>

Word of Caution: It is not recommended to pass your model directly to your view. you can rather make a view model that is tailored to the needs of that particular view and you can populate and pass this view model to the view.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜