27

Is there anything wrong with this html? I want to have a link in the masterpage to navigate to "CreateParts" view. I have action 'CreateParts' which have a parameter parentPartId in the controller 'PartList'.

<li id="taskAdminPartCreate" runat="server">
                                    <%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 })%></li>

My controller action is like

public ActionResult CreateParts(int parentPartId)
    {
        HSPartList objHSPart = new HSPartList();
        objHSPart.Id = parentPartId;
        return View(objHSPart);
    }

When I click on 'Create New Part' in the menu in SiteMaster, I get exception. Please help me out of this.

Suja Shyam
  • 971
  • 2
  • 27
  • 57
  • 2
    Adding the exception to the question would be nice :) – Øyvind Bråthen Nov 28 '11 at 09:40
  • 14
    dude, what the hell is runat=server doing on that poor li ? dont rape MVC :) – rouen Nov 28 '11 at 09:52
  • rouen, can you help with best practices in asp.net mvc – Suja Shyam Nov 28 '11 at 10:25
  • that is not best practice, that is fundamental concept. Learn, what runat=server is doing in WebFroms, and why it is not needed in MVC. I recommend starting with some reading of "background" stuff like patterns behind WebForm and MVC – rouen Nov 28 '11 at 13:34

3 Answers3

65

You are using incorrect overload. You should use this overload

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    Object routeValues,
    Object htmlAttributes
) 

And the correct code would be

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>

Note that extra parameter at the end. For the other overloads, visit LinkExtensions.ActionLink Method. As you can see there is no string, string, string, object overload that you are trying to use.

archil
  • 39,013
  • 7
  • 65
  • 82
10

You are using the incorrect overload of ActionLink. Try this

<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>
krolik
  • 5,712
  • 1
  • 26
  • 30
9

Addition to the accepted answer:

if you are going to use

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)

this will create actionlink where you can't create new custom attribute or style for the link.

However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.

 @Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })