【问题标题】:ASP.NET MVC Attribute-Routing with Null Values具有空值的 ASP.NET MVC 属性路由
【发布时间】:2016-08-14 15:25:28
【问题描述】:

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

当存在 MovieId 和 CustomerId 的值时,路由成功并呈现页面

例如/一切/MovieCustomer/1/1

如果其中一个或两个值为空,我希望页面也能加载。到目前为止,两个 int 参数都可以为空,并且如果其中一个为空,则方法中有一个 if 语句将参数更改为 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);
}

【问题讨论】:

标签: c# asp.net asp.net-mvc


【解决方案1】:

您可以使用单独的路由来实现这一点,或者将您的参数更改为可选的。

当使用 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
}

或者,您可以将路由参数更改为可选(通过在路由定义中添加 ?),这应该涵盖您拥有的所有 3 种情况:

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

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

【讨论】:

  • 这是正确的...我的:[Route("/KodePos/Print/{sKeyword?}")] public IActionResult Print(string?sKeyword) {}
【解决方案2】:

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

检查一下。如果您确实只想提供 customerId,我认为您可以将多路由方法与 EVEN ANOTHER 路由一起使用:

[Route("Everything/MovieCustomer/null/{customerId}")]

【讨论】:

    【解决方案3】:

    有趣的是,我还必须在签名中添加可选参数,以便它可以像这样在 Angular 客户端上工作:

    [HttpGet]
    [Route("IsFooBar/{movieId?}/{customerId?}")]
    [Route("IsFooBar/null/{customerId?}")]
    public bool IsFooBar(int? movieId = null, int? customerId = null)
    {
        // the rest of the code
    }
    

    在 Angular 中

      public IsFoobar(movieId: number | null, customerId: number | null): Observable<boolean> {
        return this.httpService.get<boolean>(`api/IsFooBar/${movieId}/${customerId}`);
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-10
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多