将两个可选参数传递给 RedirectToRoute

Passing Two Optional parameter to RedirectToRoute

我将 2 个可为 null 的参数传递给 Products 操作。但是我不得不在 mallId 中传递一些值,否则我会收到 no route table matches found 错误。我想在 mallId 中传递 null 并在 Products 操作中接收。

return RedirectToRoute("Products",
                      new
                      {   
                          mallId =(Int32?)null,
                          storeId =(Int32?)storeProducts.StoreId
                      });


[Route("Mall/{mallId?}/Store/{storeId?}/Products", Name = "Products")]
public ActionResult Products(string mallId, long? storeId)
{
    return View(products);
}

属性路由让我头疼,但它也很棒。

[Route("Mall/{mallId?}/Store/{storeId?}/Products", Name = "Products")]
public ActionResult Products(string mallId = null, long? storeId)
{
    return View(products);
}

并且不要传入 mallId 的值

您应该为 mallId 提供一个默认值。您分配参数的方式使得不可能在路由组合中不提供 mallId:

[Route("Mall/{mallId=all}/Store/{storeId?}/Products", Name = "Products")]
public ActionResult Products(string mallId = "all", long? storeId = null)
{
    if(mallId == "all")
       //do something

    return View(products);
}