mapping the true or false values to active inactive in ASP.NET MVC -
i working on test application student records. displaying in html table grid. convert value true or false active/inactive. 0 or 1 value male/female.
db
[id] int identity (1, 1) not null, [studentname] varchar (100) not null, [rollno] int not null, [address] varchar (200) not null, [sex] int not null, [active] bit null, primary key clustered ([id] asc)
model
public class student { public student(); public bool? active { get; set; } public string address { get; set; } public int id { get; set; } public int rollno { get; set; } public int sex { get; set; } public string studentname { get; set; } }
view
<div class="table-responsive"> <table class="table table-condensed table-bordered table-responsive table-hover" > <thead> <tr> <th>student name</th> <th>student roll no</th> <th>student sex</th> <th>student address</th> <th>status</th> </tr> </thead> <tbody> @foreach (var item in model.students) { <tr> <td>@item.studentname</td> <td>@item.rollno</td> <td>@item.sex</td> <td>@item.address</td> <td>@item.active</td> </tr> } </tbody> </table>
controller
[authorize] public actionresult index() { schooldbentities db = new schooldbentities(); studentvm vm = new studentvm(); vm.students = db.students.tolist(); return view(vm); }
you can use ternary operator
<td>@(item.active ? "active" : "inactive")</td> <td>@(item.sex==1 ? "female" : "male")</td>
if active
property nullable bool, need check property null before doing value comparison.
<td> @if (item.active!= null) { @(item.active.value ? html.raw("active") : html.raw("inactive")) } </td>
the above code render active or inactive based on value active property value if not null
. if null
, not print anything.
you can perhaps move helper method view cleaner.
edit : as per comment, want
if null or false 'inactive" else "active"
you can add null check before checking value 'true`
<td>@(item.active!=null && item.active.value ? "active" : "inactive")</td>
Comments
Post a Comment