I have a view model with nested Size
object:
public class RedirectViewModel
{
public Size Size { get; set; }
}
Size class:
public class Size
{
public int Height { get; set; }
public int Width { get; set; }
}
I would like to have properties of the Size
object filled by the route values I'm passing using redirection.
public class HomeController : Controller
{
public IActionResult Index()
{
return RedirectToAction(nameof(Redirect), new { Size = new { Width = 20, Height = 40 } } );
}
public IActionResult Redirect([FromRoute] RedirectViewModel viewModel)
{
return View(viewModel);
}
}
What I am getting out of this is a redirection URL with query parameters:
?Size=%7B%20Width%20%3D%2020,%20Height%20%3D%2040%20%7D
which URL decoded comes to:
?Size={ Width = 20, Height = 40 }
Yes, the spaces are there too, I did not add them for clarity.
Sadly, this does not work. No properties are filled. But if I manually type in parameters written in such way:
?Size.Width=20&Size.Height=40
then the model binder will successfully recognize them and as a result will set the corresponding properties, as opposed to mentioned earlier URL.
I don't want to manually tweak over query parameters to get it working.
Question
How to construct the route values for properties of a nested object, so model binder recognizes them?
EDIT:
To ease the understatement of my problem I did not use the exact objects I was using. The Size struct I used in original code sample was somehow not binding correctly, so I changed it too my own class which is closer to the original scenario. Apologizes for that, I should have checked it before posting a question. Original question still states unchanged.
EDIT #2:
I found similar question for ASP.NET MVC 5. @ant-p answer suggest using RouteValueDictionary and then passing it to route values. It is not perfect, because it involves manually writing property names, which doesn't have to be bound using the exact property name e.g. when annotated with FromQueryAttribute.