Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter to controller action from a Html.ActionLink

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.

like image 338
Suja Shyam Avatar asked Nov 28 '11 09:11

Suja Shyam


People also ask

What is HTML ActionLink ()?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

How do I pass an object in ActionLink?

If you need to pass through the reference to an object that is stored on the server, then try setting a parameter of the link to give a reference to the object stored on the server, that can then be retrieved by the action (example, the Id of the menuItem in question).


1 Answers

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.

like image 109
archil Avatar answered Sep 26 '22 07:09

archil