Redeemed1
Redeemed1

Reputation: 4030

Passing ViewModel in ASP.Net MVC from a View to a different View using Get

I have a List View which has a strongly typed ViewModel which includes the entity list I am working with together with some other session-type stuff I am carrying aruound.

On clicking an item in the list (an Html.ActionLink) to go to the Details view I can easily pass the entity id. But I also want to pass the rest of the ViewModel from the View.

I can build the ActionLink with various QueryString parameters and then a custom ModelBinder can pick them up and hydrate the ViewModel object for me again. However, I don´t like this.

I can get the custom ViewModel to rehydrate when it is POSTed back to the same page etc., but how can I get the ViewModel into a Controller Action using a GET to another View without using a ModelBinder and by simply placing the ViewModel object as a parameter in the target Action method?

Upvotes: 2

Views: 5846

Answers (2)

mxmissile
mxmissile

Reputation: 11682

I just tried this, and it seemed to work. Also tried the without a form and it worked also. Not sure if this is exactly what you wanted though.

Action

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index(TestModel model)
{
  ViewData["Message"] = model.Test1;
  return View();
}

Model

public class TestModel
{
  public string Test1 { get; set; }
  public string Test2 { get; set; }
}

View

<% using (Html.BeginForm("Index","Home",FormMethod.Get))
{ %>
        <%=Html.TextBox("Test1")%>
        <%=Html.TextBox("Test2")%>
        <input type=submit value=submit />
<% }%>

Upvotes: 0

David Andres
David Andres

Reputation: 31791

I don't think you can do what you want, which from what I gather is the following:

  1. While rendering the List action, you want to create a link to another action (potentially on another controller, but that's not key here)

  2. This action should, when fired, have access to the original ViewModel that existed when the ActionLink method was first executed.

Unfortunately, items #1 and #2 are completely disconnected from each other and so there is no real mechanism to pass the current ViewModel to a link that will be executed in a different session.

That's not to say there aren't workarounds, of course:

You can generate the action link like so:

<%= 
    Html.ActionLink( 
                    "Label", 
                    "Action",  
                    "Controller",
                    new {Parameter1 = Model.Data1, Parameter2 = Model.Data2},
                    null
                   ) 
%> 

Within your linked action method, you can instantiate the ViewModel using the parameters passed to that action method.

Upvotes: 1

Related Questions