1

In MVC Core you can use:

RedirectionToAction(Action, Controller, model)

The model properties are then converted to QueryString parameters.

However, if one of the properties of the model is a List then that particular property is not correctly added to the QueryString.

For example if a property is a List of Shirt objects and has the name Shirts, then the query parameter is added as:

Shirts=NameSpace.Models.Shirt

as opposed to:

Shirts[0].Color="red"&Shirts[1].color="blue"

Does anyone know how to correctly serialize this so that the QueryString gets created correctly?

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
user2981411
  • 859
  • 12
  • 34

1 Answers1

0

Sending complex models in RedirectionToAction() indicates a design flaw. I cannot think of any good reason for this. Complex models should be coming to your actions from form submits (or Ajax submits) or similar user actions, not from your own code of other actions. Redirects should be either parameter-less or with very few simple parameters. That's probably why the RedirectionToAction() is not bothered with serializing your list.

Having said that, if you insist on doing it that way, nothing stops you from doing the serialization by yourself. It's fairly simple.

First, no double quotes around the values in the query string.

Second, for simple array properties, the syntax property[0]=value&property[1]=value will work. Also for object propertied, the dot notation property.property=value will work too. But for a list of objects property like in your question, you can try using the dot notation Shirts[0].Color=red like you mentioned. I haven't tried it myself to see if the controller can bind to it successfully. I will continue this answer with the assumption that it can, because your question is about the serialization.

Let's say the Shirt class has also an integer Size property. And let's say your model is an order with an integer Id and a decimal Total properties, in additions to the list Shirts property. You can serialize your model like this:

var qs = $"?Id={model.Id}"
        + "&Total={model.Total}";

for(var i = 0; i < model.Shirts.Count(); i++) {
  var s = model.Shirts[i];
  qs += $"&Shirts[{i}].Size={s.Size}"
       + "&Shirts[{i}].Color={HttpUtility.UrlEncode(s.Model)}";
}

I didn't handle the case if Shirts can be null, you can do so if required.

Now, you pass the query string to Redirect(). You can use Url.Action() to create the URL itself (i.e. before the query string):

Redirect(Url.Action(Action, Controller, model) + qs);
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55