以下是EverythingController中操作方法MovieCustomer的粘貼。 Viewmodel用於組合兩種模型:客戶&電影,並通過ApplicationDbContext(_context)從數據庫填充信息。帶有空值的ASP.NET MVC屬性路由
的定線制工作順利,並呈現時,有對MovieId和客戶編號
例如值的頁面/ Everything/MovieCustomer/1/1
我希望頁面也可以加載,如果其中一個或兩個值爲空。到目前爲止,這兩個int參數都是可以爲空的,並且如果兩個參數都爲空,那麼方法中會有一個if語句將參數更改爲1。 到目前爲止,如果值爲空,瀏覽器將返回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);
}
非常好,謝謝。 – Aarondv1