Hide webgrid column “Edit” link based on condition

2019-08-02 12:30发布

问题:

I have a webgrid MVC3 contains 4 columns Name, Address, age & Edit. I want to hide Edit link for row if age is greater than 55. Help me to do it.

Is there any event like OnItemDataBound event?

Thank you

回答1:

Is there any event like OnItemDataBound event?

No, there is no such concept as events in ASP.NET MVC.

You could use a custom format column.

Model:

public class PersonViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public int Age { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var persons = new[]
        {
            new PersonViewModel { Id = 1, Name = "u 1", Address = "a 1", Age = 54 },
            new PersonViewModel { Id = 2, Name = "u 2", Address = "a 2", Age = 55 },
            new PersonViewModel { Id = 3, Name = "u 3", Address = "a 3", Age = 56 },
        };
        return View(persons);
    }
}

View:

@model IEnumerable<PersonViewModel>
@{
    var grid = new WebGrid(Model);
}

@grid.GetHtml(
    columns: grid.Columns(
        grid.Column("Name"),
        grid.Column("Address"),
        grid.Column("Age"),
        grid.Column(
            header: "Edit", 
            format: 
                @<text>
                @if (item.Age < 56) 
                { 
                    @Html.ActionLink("Edit", "Edit", new { id = (int)item.Id }) 
                }
                </text>
        )
    )
)

Obviously the fact that you have hidden the link doesn't relieve you from the burden to perform the same check against the Age inside the Edit controller action given the person id. There's nothing preventing a user from entering the url of this Edit action directly in his browser address bar.