I know this sound somewhat off-piste but how开发者_StackOverflow would you create a weakly typed view where you pass in a collection of objects and iterate in razor accordingly and display in a table?
-- Controller View -- ???
-- Razor View ---
@foreach (var item in Model)
{
<tr>
<td>
@item.attr1
</td>
<td>
@item.attr2
</td>
</tr>
}
Frist you know the data send From Controller -------> view by two way
- By weak type view
- and by strong type view
there is no other way of passing data from controller to view ...(remember)
what is intelliscence ----> which show the related sub property of any model like we write Model. --------> then all property show in droupdown list after dot(.).
A.what is weak type view
- This is used without using model i.e like using ViewBag and other.
- There is no intellisence for this type of view and it is complicated, and when you write any name which not exist then it give at runtime error.
Ex.
.............Controller
ViewBag.List = List<job>;
return View();
.............Razor View
@foreach(var item in ViewBag.List)
{
// when you write no intellisence and you want to write your own correct one...
@item.
}
B. What strongly type view
- this is used model to send data from controller to view an vice-versa.
- Model are strongly typed to view so, it show intellicence and when you write wrong then there only error show at compile time..
Ex.
.................Controller
List<job> jobdata =new List<job>();
return View(jobdata);
................view
//Mention here datatype that you want to strongly type using **@model**
@model List<job>
@foreach(var item in Model)
//this **Model** represent the model that passed from controller
// default you not change
{
@item. //then intellisence is come and no need write own ....
}
that is weak and strong type view ...... So now you solve any problem with this basic..... may I hope it help u....
But it is best to use Strongly Typed view so it become easy to use and best compare to weak...
@model dynamic
Will do what you want, I believe.
If its going to be a collection, then maybe use
@model ICollection
It's not weakly typed. It's typed to a collection of some kind.
@model IEnumerable<MyClass>
OK, late to the party I know, but what you're after is a view stating "@model dynamic" as already stated.
Working Example: (in mvc3 at time of posting)
NB In my case below, the view is actually being passed a System.Collections.IEnumerable As it's weakly typed, you will not get intelesense for the items such as @item.Category etc..
@model dynamic
@using (Html.BeginForm())
{
<table class="tableRowHover">
<thead>
<tr>
<th>Row</th>
<th>Category</th>
<th>Description</th>
<th>Sales Price</th>
</tr>
</thead>
@{int counter = 1;}
@foreach (var item in Model)
{
<tbody>
<tr>
<td>
@Html.Raw(counter.ToString())
</td>
<td>
@item.Category
</td>
<td>
@item.Description
</td>
<td>
@item.Price
</td>
</tr>
@{ counter = counter +1;}
</tbody>
}
</table>
}
Edit: removed some css
精彩评论