Hide webgrid column “Edit” link based on condition in MVC3

前提是你 提交于 2020-01-24 19:50:06

问题


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.



来源:https://stackoverflow.com/questions/12937450/hide-webgrid-column-edit-link-based-on-condition-in-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!