In the WebGrid last column has 3 buttons “create, edit, delete”. As indicated in the title I want to show only “edit” and “delete” buttons if the user is authenticated and authorized.
If the link is not in the WebGrid, for example “Add” button I can do that in this way:
<div >
@if (Request.IsAuthenticated && (User.IsInRole("Admin") || User.IsInRole("canEdit")))
{
<a class="btn btn-success" href="@Url.Action("Create" )" id="btnCreate"><i class='glyphicon glyphicon-plus'></i> </a>
}
</div>
In the grid I have formatted the last column in this way:
grid.Column(header: "Action", canSort: false, style: "action col-lg-2",
format: (item) => new HtmlString("<a href=" + @Url.Action("Details", new { id = item.id }) + " title='Detail' ><i class='glyphicon glyphicon-search'> </i><span class='sr-only'>Detail</span> </a> "
+ " <a href=" + @Url.Action("Edit", new { id = item.id }) + "><i class='glyphicon glyphicon-edit'></i><span class='sr-only'>Edit</span> </a> "
+ " <a href=" + @Url.Action("Delete", new { id = item.id }) + "><i class='glyphicon glyphicon-trash'> </i> </a> ")
)
And it works perfectly. But I am unable to figure out how to put if statement inside the lambda expression. How can I do that?
Here is the code:
var grid = new WebGrid(canPage: true, rowsPerPage: Model.PageSize, canSort: true, ajaxUpdateContainerId: "grid");
grid.Bind(Model.Content, rowCount: Model.TotalRecords, autoSortAndPage: false);
@grid.GetHtml(htmlAttributes: new { id = "grid" }, // id for ajaxUpdateContainerId parameter
fillEmptyRows: false,
tableStyle: "table table-bordered table-hover",
mode: WebGridPagerModes.All,
columns: grid.Columns(
grid.Column("Id", "ID", style: "col-lg-1"),
grid.Column("ProductName", "Name", style: "col-lg-3"),
grid.Column("Description", "Description", style: "col-lg-5"),
grid.Column(header: "Action", canSort: false, style: "action col-lg-2",
format: (item) => new HtmlString("<a href=" + @Url.Action("Details", new { id = item.id }) + " title='Detail' ><i class='glyphicon glyphicon-search'> </i><span class='sr-only'>Detail</span> </a> "
+ " <a href=" + @Url.Action("Edit", new { id = item.id }) + "><i class='glyphicon glyphicon-edit'></i><span class='sr-only'>Edit</span> </a> "
+ " <a href=" + @Url.Action("Delete", new { id = item.id }) + "><i class='glyphicon glyphicon-trash'> </i> </a> ") )
)
);