如何在控制器方法中添加虚拟类作为参数?

问题描述 投票:1回答:2

我的控制器包含

 [Route("/sales")]
 public IActionResult Index()
 {
     Model myModel = new Model();
     return test(DateTime.Today, DateTime.Today, myModel);
 }

和测试方法

[HttpPost]
[ValidateAntiForgeryToken]
[Route("/sales/{startDate}/{endDate}/{myModel}")]
public IActionResult test(DateTime startDate, DateTime endDate, Model myModel = null)
{
    myModel ??= new Model();
    return View(myModel);
}

在页面加载中,所有内容均按预期工作。索引方法,将模型传递给测试功能。

不幸的是,当AJAX发布发生在

/sales/2020-05-14/2020-05-14/null

我收到内部服务器错误(500),这似乎是合乎逻辑的。

但是我该如何解决?有什么属性可以修饰可选参数Model myModel = null

实际上,当我从客户端调用此属性时,我想将此属性视为虚拟属性,这就是为什么我将其设置为null。

c# asp.net-mvc asp.net-core asp.net-web-api
2个回答
0
投票

From MSDN:

方法,构造函数,索引器或委托的定义可以指定其参数是必需的还是可选的。任何调用都必须提供所有必需参数的参数,但是可以省略可选参数的参数。

由于myModel参数是可选的,因此您可以从ajax调用中忽略它。 要省略此参数,您还需要在路由中将此参数设为可选参数,

[HttpPost]
[ValidateAntiForgeryToken]
[Route("/sales/{startDate}/{endDate}/{myModel?}")]
public IActionResult test(DateTime startDate, DateTime endDate, Model myModel = null)
{
    myModel ??= new Model();
    return View(myModel);
}

1
投票

要将route参数标记为可选,请使用“?”。所以它看起来像这样:


    [HttpPost]
    [ValidateAntiForgeryToken]
    [Route("/sales/{startDate}/{endDate}/{myModel?}")]
    public IActionResult test([FromRoute] DateTime startDate, [FromRoute] DateTime endDate, [FromRoute] Model myModel = null)
    {
        myModel ??= new Model();
        return View(myModel);
    }

© www.soinside.com 2019 - 2024. All rights reserved.