Wednesday, April 20, 2011

ASP.NET MVC. No idea how to use Url.action to pass an object to the controller

I am new to asp.net MVC. I was able to create my view and display the data (Gridview). Additionally, I was able to create a hyperlink (using Url.Action) passing string and int types. However, I want to create a hyperlink that it is referencing a more complex type. The class associated with my view has a reference to a List. What I want is to create an additional ActionResult in my controller that gets as a parameter List (See below)

public ActionResult ViewItems(List<Items> c)
{            
    return View(c);
}

My idea is when is to be able to pass that List to the controller and then the controller will call the corresponding view. I tried (See below) but I just get blank.

<asp:HyperLink ID="LinkContractID" runat="server" NavigateUrl='<%#Url.Action("ViewItems", new {c = **((Contract)Container.DataItem).ContractItems.ToList<Items>(**)}) %>'
Text='<%# Eval("ContractId") %>'></asp:HyperLink>
From stackoverflow
  • If you are looking for a grid, this tutorial shows how to create a grid with MVC.

  • With MVC, you shouldn't use Gridview and asp: controls. If you want to generate a link, just use <%=Html.ActionLink(...) %> with the necessary parameters.

  • Like in the previous answer, you don't use asp controls. There are pros and cons with Html.ActionLink however, it isn't so good if you want to put a link around an image for instance. In this case the syntax would be

    <a href="<%= Url.Action(
       "ShowListPage", "MyController", new { modelId = 101 }) %>">
       <img src="img.gif" />
    </a>
    

    Also with your action in the controller, you would ideally be looking to have this go and get the model to pass to a view strongly typed to this model. So you have a model object with a constructor taking an id, for instance

    public MyModel(int modelId)
    {
       this.TheListThatHoldsTheGridData = MyDataLayerProc(modelId);
    }
    

    This way you can have your action in the MyController controller, return the view ShowListPage (associated with a MyModel instance) like so

    public ActionResult ShowListPage(int modelId)
    {
       return View(new MyModel(modelId));
    }
    

    Hope this helps,

    Mark

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.