Search code examples
c#asp.net-mvclambdawebgrid

How to convert WebGrid column's int value to string?


I am using WebGrid to display data from Model. I want that ID column should be hyperlink. So, when anyone click on ID,it's corresponding page will be open. I have tried following code, but I am getting error: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot convert type 'int' to 'string'

CODE:

grid.Column(columnName: "ID", header: "ID", canSort: true, format: item => Html.ActionLink((string)item.ID, "../CRM/DetailsRequest", new { ID = item.ID })),....

Solution

  • It looks like the ID property is an integer, so you cannot cast it to string. Try casting it to an integer first:

    grid.Column(
        columnName: "ID", 
        header: "ID", 
        canSort: true, 
        format: item => Html.ActionLink(
            ((int)item.ID).ToString(), 
            "DetailsRequest", 
            "CRM", 
            new { ID = item.ID }, 
            null
        )
    )
    

    Or if in your view model you had another string property which you would like to use as the anchor text:

    grid.Column(
        columnName: "ID", 
        header: "ID", 
        canSort: true, 
        format: item => Html.ActionLink(
            (string)item.Name, 
            "DetailsRequest", 
            "CRM", 
            new { ID = item.ID }, 
            null
        )
    )