Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am new to MVC design pattern. I use Entity Framework to get records and i want to display those records as a Link Button. When i use tag i can able to display record but when i use @Html.ActionLink i am getting Value cannot be null or empty. The code as follows,

Working:
@foreach (var items in Model)
{
@items.name

}

Not Working:
@foreach (var items in Model)
{
@Html.ActionLink(@items.name, "Details", "Home", new object { @items.id})
}

Thanks in Advance :-)

What I have tried:

Mentioned above code was i tried
Posted
Updated 13-Aug-17 22:57pm

1 solution

@Html.ActionLink(items.name, "Details", "Home", new { id = items.id }, null)


You only need the "@" proceeding something when you want to write the result of it to the html. So it's needed in front of Html.ActionLink but not with the parameters as you're passing those as values, not writing them directly to the html.

When passing the attributes you use what's called an anonymous type (the new { .. } statement) and that needs to be of the format {propNameA = propValueA, propNameB = propbValueB}. Lastly you need to use the right overload for ActionLink that does what you want. The one you want has 5 params, the last one being any html attributes you want on the link, but we don't need any so we supply "null" as the 5th param. If you didn't supply that null then you only have 4 parameters and it uses a different overload where the params mean different things and you won't get what you want. It's a strange quirk of MVC.
 
Share this answer
 
v2
Comments
Maniraj.M 14-Aug-17 5:54am    
I modified the code like this but still i am geting same error! ;(
Html.ActionLink(@items.name, "Details", "Home", new { id = @items.id}, null);
F-ES Sitecore 14-Aug-17 5:56am    
Check that neither items.Name nor items.id is null. You're also still using "@" when you don't have to.
Maniraj.M 14-Aug-17 6:04am    
i modified code to ,
if(!string.IsNullOrEmpty(items.name))
{
@Html.ActionLink(items.name, "Details", "Home", new { id = items.id}, null)
}

its working fine now. Thanks a lot!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900