kingrichard2005
kingrichard2005

Reputation: 7269

Passing data from a View to a controller in ASP.Net MVC

I have a dictionary I'm passing to a View. I want to be able to pass the values of that dictionary back to a Controller action from this same View. Is there anyway this can be accomplished without using a form? The situation is that I need to be able to pass these back to a controller action that is called when a user clicks an ActionLink from the View, and in my experience an ActionLink cannot be used to submit a values of a form, i.e. I've only been able to submit values of a form using the form's submit button. Unless there's a way to use an ActionLink to submit values in a form.

Controller Action passes Dictionary to Controller in ViewData:

public ActionResult ModifyNewCrossListing(FormCollection form)
        {
            Dictionary<int, string> prefixlist = new Dictionary<int, String>();
            ViewDatap["prefixList"] = prefixlist;
        }

View prints out content of Dictionary, ActionLink calls another controller action, which is where I want to access the dictionary:

<%int i = 0;
      if ((ViewData["prefixList"] as Dictionary<int, string>).Count >= 1)
      {
          foreach (var cp in (ViewData["prefixList"] as Dictionary<int, string>))
          {
              if (cp.Value == (ViewData["prefixList"] as Dictionary<int, string>).Last().Value)
              {%>
                  <%= Html.Encode(cp.Value)%>
              <%}
              else
              {%>
                  <%= Html.Encode(cp.Value)%> -
            <%}
          } 
      } %> 

<%=Html.ActionLink("View All Criteria", "ShowAllCriteria", new { prefixList = ViewData["prefixList"] as Dictionary<int, string> })%>)

And finally, in my new controller action, I want to be able to access the dictionary

public ActionResult ShowAllCriteria(Dictionary<int, string> prefixList)
        {
          //Do stuff
        }

Upvotes: 0

Views: 1292

Answers (1)

Robert Harvey
Robert Harvey

Reputation: 180787

Without a button or form, I would say that your best bet is to hook the link to a Javascript or jQuery method, and post the data back to the controller using AJAX or JSON.

The controller method can then perform the necessary redirect to display a new page.

Upvotes: 1

Related Questions