Search code examples
c#asp.netasp.net-mvcasp.net-mvc-5webgrid

How To Change The URL Of A Link In A WebGrid Depending On Clients Age


I have a List<WebGridColumn>table that displays a list of clients, both adult and child. Depending on the clients age they have a different URL so adults are /secure/client/[Page URL] and a child's is /secure/junior/[Page URL].

The issue I have is that I cant figure out how to make my link the user clicks direct them to the correct URL.

Below is what I have that doesn't work:

List<WebGridColumn> cols = new List<WebGridColumn>();
        cols.Add(new WebGridColumn { Header = "Client name", ColumnName = "ClientName", CanSort = true, Format = (item) => String.Format("<a onclick=\"showPopUp()\" href=\"/Secure/Adviser/Client/?ClientIdentifier={0}\">{1}</a>", item.Identifier, item.ClientName) });
        cols.Add(new WebGridColumn { Header = "Account number", ColumnName = "AccountNumber", CanSort = true });
        foreach (ClientViewColumn c in currentClientView.Columns)
        {

This works fine for adults due to the href set

I have tried adding an ifstatement around it but this causes a server error as show below:

List<WebGridColumn> cols = new List<WebGridColumn>();
        if (AJBG.CMS2.Sippcentre.AppCode.Functions.UserDetails.IsJunior())
        {
            cols.Add(new WebGridColumn { Header = "Client name", ColumnName = "ClientName", CanSort = true, Format = (item) => String.Format("<a onclick=\"showPopUp()\" href=\"/Secure/Adviser/Junior/?ClientIdentifier={0}\">{1}</a>", item.Identifier, item.ClientName) });
        }
        else
        {
            cols.Add(new WebGridColumn { Header = "Client name", ColumnName = "ClientName", CanSort = true, Format = (item) => String.Format("<a onclick=\"showPopUp()\" href=\"/Secure/Adviser/Client/?ClientIdentifier={0}\">{1}</a>", item.Identifier, item.ClientName) });
        }   
        cols.Add(new WebGridColumn { Header = "Account number", ColumnName = "AccountNumber", CanSort = true });
        foreach (ClientViewColumn c in currentClientView.Columns)
        {

How do I do it as I cant think of a way to.

Thanks


Solution

  • Declare the variable in your view as follows:

    var isJunior = AJBG.CMS2.Sippcentre.AppCode.Functions.UserDetails.IsJunior();
    

    Then evaluate it as follows in your string.Format:

     (isJunior ? "Junior" : "Client")
    

    Your code would then become this:

        var isJunior = AJBG.CMS2.Sippcentre.AppCode.Functions.UserDetails.IsJunior();
        List<WebGridColumn> cols = new List<WebGridColumn>();
            cols.Add(new WebGridColumn { Header = "Client name", 
            ColumnName = "ClientName", CanSort = true, 
            Format = (item) => 
            String.Format("<a onclick=\"showPopUp()\" href=\"/Secure/Adviser/{2}/?ClientIdentifier={0}\">{1}</a>", item.Identifier, item.ClientName, (isJunior ? "Junior" : "Client")) });
    ...