Search code examples
c#asp.net-mvcviewviewmodel

ASP.NET MVC & C# : pass a viewmodel to controller


I have a controller that passes the viewmodel to a view, and in the view it creates the table correctly.

Then in the same page of the table I have a link that redirects the user to another page.

This new page needs to keep the viewmodel of the previous view. How could I do it?

In the view, in the table page this link that should redirect to an action of EanMatch controller:

@Html.ActionLink("Inserimento manuale", "Index", "EanMatch",  null, new {Vm = Model})

The model is this:

public List<DDTViewModel> DDTList { get; set; }

In the EanMatchController and Index action I have:

[HttpGet]
public ActionResult Index(DDTListViewModel Vm)
{
    ....
}

I can't understand why it doesn't work. DDTListViewModel Vm in Index actions takes 'null' value, meanwhile I have seen with debug that Model got the list of data.

How can I pass the viewmodel to the action argument correctly?

Any doubt, ask !


Solution

  • For your particular case, You'll have to serialize your model as a JSON string, and send that to your controller to turn into an object.

    Here's your ActionLink:

    @Html.ActionLink("Inserimento manuale", "Index", "EanMatch",  new { jsonModel= Json.Encode(Model.DDTListViewModel) }, null)
    

    And your Controller method would look like:

    public ActionResult Index(string jsonModel)
    {
      var serializer= new DataContractJsonSerializer(typeof(Model.DDTListViewModel));
      var yourmodel=  (DDTListViewModel)serializer.ReadObject(GenerateStreamFromString(jsonModel));
    }