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

守給你的承諾、 提交于 2019-12-04 15:59:45

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.

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 />
<% }%>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!