Passing ViewModel in ASP.Net MVC from View to Another View using Get
I have a List View that has a strongly typed ViewModel that includes a list of entities that I am working with along with some of the other session types that I carry with.
When clicking on an item in the list (Html.ActionLink) to go to the Details view, I can easily pass in the id of the object. But I also want to pass the rest of the ViewModel from the view.
I can create an ActionLink with different QueryString parameters and then the custom ModelBinder can pick them up and pop the ViewModel again. However, I don't like this.
I can get the custom ViewModel to re-register when it is posted back to the same page and so on, but how can I get the ViewModel into the controller action using GET for another view without using the ModelBinder and just putting the ViewModel object as a parameter in the target method of action?
source to share
I don't think you can do what you want, which from what I collect is as follows:
-
When rendering a List action you want to create a link to another action (maybe on a different controller, but that's not a key)
-
This activity must, when launched, have access to the original ViewModel that existed when the ActionLink method was first run.
Unfortunately, items # 1 and # 2 are completely disconnected from each other, so there is no real mechanism for passing the current ViewModel into a link that will be executed in another session.
Not to say that there are no workarounds, of course:
You can create an action link like this:
<%=
Html.ActionLink(
"Label",
"Action",
"Controller",
new {Parameter1 = Model.Data1, Parameter2 = Model.Data2},
null
)
%>
Within your bound actions method, you can instantiate the ViewModel using the parameters passed to that action method.
source to share
I just tried this and it seemed to work. Also tried without form and it worked too. Not sure if this is exactly what you wanted.
Act
[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 />
<% }%>
source to share