I have an application in MVC5/C#
My index view is a simple list from a model. I added an additional html actionlink to view the history of any selected item. With this link, I am going to a different controller (ICS_HistoryView) and passing an id parameter.
Originally it broke because some of the items (Old_ItemID field) have / in them, causing the link to break. So, after some research, I learned that I can use Replace to replace / with -, so the url will not break and then switch it back in the controller of the new view. However, I am getting a null error when the view loads, on this line
@Html.ActionLink("History", "History", "ICS_HistoryView", new { id = item.Old_ItemID.Replace('/', '-')}, null)
But, without the Replace, it loads properly. Only when I click the History link, does the url break with the / in the parameter.
@Html.ActionLink("History", "History", "ICS_HistoryView", new { id = item.Old_ItemID}, null)
Can someone help me understand why it becomes null when I use replace and breaks the code?
I can provide the controller code if needed, but it's really simple. This is just a list view.
Example:
Old_ItemID = VNC/2/1
Without the Replace, I get the correct url with parameter VNC/2/1 but I get page not found, obviousl
Adding Replace, I get a null error - and I don't understand why
The only reason I suspect for this error is when item.Old_ItemID
is null
.
Otherwise it works fine for string with any value including empty string.
Could you try adding null-condition operator like item.Old_ItemID?.Replace("/","-")
For best practice, I would suggest such manipulations in Model/Domain classes.
Create a Get property or a method in Item (or whatever class that is)
to replace tokens in URL.
i.e.
public string OldItemIdForUrlGeneration => this.Old_ItemID.Replace("/", "-");
and then
@Html.ActionLink("History", "History", "ICS_HistoryView", new { id = item.OldItemIdForUrlGeneration }, null)