路由从另一路由中未能正确获取参数。

huangapple go评论65阅读模式
英文:

Route never get the correct parameters sent from another route

问题

我有一个在.NET Core 7.0中使用C#10编写的非常简单的MVC控制器。

问题是,在Index方法中,我发送到Calculate方法的值从未到达,它总是到达VolatilityViewQueryModel类的新实例。为什么会这样?

提前感谢。

英文:

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

答案1

得分: 2

这是因为您使用匿名类型调用Index方法,但它需要VolatilityViewQueryModel类型。因此,MVC会创建一个新的空实例VolatilityViewQueryModel并将其传递给Index操作方法。

使用:

return RedirectToAction(nameof(Index), query);
英文:

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);

答案2

得分: 0

由于它是相同的控制器,您可以使用更简单的代码:

return Index(query);
英文:

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

return Index(query);

huangapple
  • 本文由 发表于 2023年3月7日 05:39:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定