具有空值的ASP.NET MVC属性路由

Aar*_*dv1 2 c# asp.net asp.net-mvc

这是EverythingController中动作方法MovieCustomer的粘贴.Viewmodel用于组合两个模型:Customer和Movies,并通过ApplicationDbContext(_context)填充来自数据库的信息.

路由功能成功运行,并在有MovieId和CustomerId值时呈现页面

例如/ Everything/MovieCustomer/1/1

如果一个或两个值为null,我希望页面也加载.到目前为止,两个int参数都是可空的,并且在方法中有一个if语句,如果其中任何一个为null,则将参数更改为1.到目前为止,如果值为null,则浏览器返回404错误.

当一个参数或其中一个参数为空时,如何使页面正常工作?谢谢

[Route("Everything/MovieCustomer/{movieId}/{customerId}")]
public ActionResult MovieCustomer(int? movieId, int? customerId)
{
    var viewmodel = new ComboViewModel
    {
        _Customers = new List<Customer>(),
        _Movies = new List<Movies>(),
        _customer = new Customer(),
        _movie =  new Movies()
    };
    viewmodel._Customers = _context.Customers.ToList();
    viewmodel._Movies = _context.Movies.ToList();

    if (!movieId.HasValue)
        movieId = 1;

    if (!customerId.HasValue)
        customerId = 1;

    viewmodel._customer = viewmodel._Customers.SingleOrDefault(a => a.Id == customerId);
    viewmodel._movie = viewmodel._Movies.SingleOrDefault(a => a.Id == movieId);

    return View(viewmodel);
}
Run Code Online (Sandbox Code Playgroud)

dot*_*tom 11

您可以使用单独的路径实现此目的,或将您的参数更改为可选.

使用3个属性时,为每个选项添加单独的路径 - 未指定参数时,仅movieId指定时间,以及指定所有3个参数时.

[Route("Everything/MovieCustomer/")]
[Route("Everything/MovieCustomer/{movieId}")]
[Route("Everything/MovieCustomer/{movieId}/{customerId}")]
public ActionResult MovieCustomer(int? movieId, int? customerId)
{
    // the rest of the code
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以将组合路线参数更改为可选(通过添加?路线定义),这应该涵盖您拥有的所有3个案例:

[Route("Everything/MovieCustomer/{movieId?}/{customerId?}")]
public ActionResult MovieCustomer(int? movieId, int? customerId)
{
    // the rest of the code
}
Run Code Online (Sandbox Code Playgroud)

请记住,两个示例都不支持您仅提供的情况customerId.