1

I have this very simple MVC controller in .net-core net7.0, using c#10

public class HomeController : Controller
{
    public IActionResult Index(VolatilityViewQueryModel model = null)
    {
        if (model is null)
        {
            model = new VolatilityViewQueryModel
            {
                BigInterval = 365,
                SmallInterval = 7
            };
        }

        return View(model);
    }

    [HttpPost]
    public IActionResult Calculate([FromForm]VolatilityViewQueryModel query)
    {
       //here i will go to a service to get some data, this is just to make the example easier to understand
        query.Data = new VolatilityResult[] { new VolatilityResult() };

        return RedirectToAction(nameof(Index), new { model = query});
    }
}

the problem is that at Index method it never arrives the value i send in the Calculate method, it always arrives a new instace of the VolatilityViewQueryModel class. Why is that?

Thanks in advance

Qing Guo
  • 6,041
  • 1
  • 2
  • 10
Kirzy
  • 138
  • 1
  • 16

2 Answers2

2

This is because you call the Index method with anonymous type, but it expect the VolatilityViewQueryModel type. Therefore, the MVC is creating a new empty instance of the VolatilityViewQueryModel and pass it to the Index action method.

Use:

return RedirectToAction(nameof(Index), query);
Jackdaw
  • 7,626
  • 5
  • 15
  • 33
  • It works indeed, my problem now its the array. The Data array contains hundreds of items and the redirect URL gets to big and it just don't work – Kirzy Mar 07 '23 at 00:30
  • @Kirzy: This problem about array was not described in your question. Try to describe all your questions in initially post, or better don't stack but split these. See solutions related to transfer data while redirecting described in the following posts: [Redirect to action and need to pass data](https://stackoverflow.com/a/3364045/6630084) or [Can we pass model as a parameter in RedirectToAction?](https://stackoverflow.com/a/22505985/6630084). – Jackdaw Mar 09 '23 at 06:49
0

since it is the same controller, you can use much more simple code

return Index(query);
Serge
  • 40,935
  • 4
  • 18
  • 45
  • when i do that i get an error "InvalidOperationException: The view 'Calculate' was not found. The following locations were searched: /Views/Home/Calculate.cshtml /Views/Shared/Calculate.cshtml" – Kirzy Mar 09 '23 at 00:01
  • @Kirzy It is really strange. It never happened. But what a view do you want to return? You can try to fix the Index action for example - return View("Index", model). – Serge Mar 09 '23 at 00:07
  • what i wanted is to return the index view and keep the same URL, because each time i do a POST the URL changes to /Home/Calculate I would like to keep it just /Home – Kirzy Mar 10 '23 at 01:03