2016-08-14 44 views
0

以下是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); 
} 

回答

4

您可以使用單獨的路徑實現此目的,或者將您的參數更改爲可選參數。

當使用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的情況。

+0

非常好,謝謝。 – Aarondv1