MVC Html Helpers

View helper sample code

1
@Html.DropDownListFor(model => model.OperatorValue, (List<SelectListItem>)ViewData["OperatorValue_SelectList"], new { @class = "form-control" })

Controller sample code, this can be in ‘Lookups.cs’ class

1
2
3
4
5
6
7
8
9
10
11
12
public static List<SelectListItem> OperatorSelectList()
{
var r = new List<SelectListItem>
{
new SelectListItem { Value = "", Text = "-- Please Select --" },
new SelectListItem { Value = "*", Text = "*" },
new SelectListItem { Value = "/", Text = "/" },
new SelectListItem { Value = "+", Text = "+" },
new SelectListItem { Value = "-", Text = "-" }
};
return r;
}

DisplayNameFor

Display from property that is a list of another class

Example:

1
2
3
4
5
6
7
8
9
10
11
12
public class AddViewModel
{
public double BaseRate { get; set; }
public DateTime EffectiveFrom { get; set; }
public List<HistoryViewModel> RatePrimeHistory { get; set; }
}

public class HistoryViewModel
{
public double BaseRate { get; set; }
public DateTime EffectiveFrom { get; set; }
}

To display the history data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<table class="table">

<tr>
<th>
@{var dummy = Model.RatePrimeHistory.FirstOrDefault(); }
@Html.DisplayNameFor(model => dummy.BaseRate)
</th>
<th>
@Html.DisplayNameFor(model => dummy.EffectiveFrom)
</th>
</tr>

@foreach (var item in Model.RatePrimeHistory)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.BaseRate)
</td>
<td>
@Html.DisplayFor(modelItem => item.EffectiveFrom)
</td>
</tr>
}

</table>

Calling IEnumerable overload of DisplayNameFor