1

My controller contains

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

and the test method

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

On page load everything works as expected. Index method, passes the model to the test function.

Unfortunatelly when an AJAX post occures at

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

i get an internal server error (500), which seems to be logical.

But how can i fix that? Is there any attribute that i can decorate the optional parameter Model myModel = null

Actually i want to treat this property as dummy when called from client side, and that is why i have set it to null.

OrElse
  • 9,709
  • 39
  • 140
  • 253
  • 1
    and what is the excpetion you get when you get the 500 error? – Georgi Georgiev May 15 '20 at 08:06
  • Optional parameter can use in this way, see the another SO https://stackoverflow.com/questions/24678045/routing-optional-parameters-in-asp-net-mvc-5 for detail. – nwpie May 15 '20 at 08:22

2 Answers2

1

To mark the route parameter as optional use the "?". So it will look like this:


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

0

From MSDN:

The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.

As your myModel argument is optional, you can omit it from ajax call. To omit this argument you need to make this parameter as an optional in route as well,

[HttpPost]
[ValidateAntiForgeryToken]
[Route("/sales/{startDate}/{endDate}/{myModel?}")]
public IActionResult test(DateTime startDate, DateTime endDate, Model myModel = null)
{
    myModel ??= new Model();
    return View(myModel);
}
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44