2017-05-08 42 views
0

我有一個將複雜對象作爲輸入的動作。我希望能夠使用POST數據或GET請求中的查詢字符串來填充任何值。這工作正常。MVC5 - 如何知道動作輸入是否完全爲空

如果沒有提供用戶輸入,我也想提供一個默認值,但是這不起作用,因爲即使GET請求中沒有查詢字符串參數,過濾器也不會爲null。相反,MVC只是調用模型的默認構造函數而不設置任何屬性,而不是給我一個null。

 public ActionResult Index(DataFilterInput filter = null) 
     { 
      if (filter == null) 
       filter = new DataFilterInput { Top = 100 }; 
      var model = new IndexModel(); 
      return View(model); 
     } 

我怎樣才能知道我是否應該在沒有用戶輸入的被拖欠的值(我不想進入請求的查詢字符串或窗體集合)?

+0

檢查模型狀態檢查和調查數據屬性 – Nkosi

+0

@Nkosi,可以請你提供一點點的細節,並提交這個作爲一個答案,而不是評論? – TheCatWhisperer

+0

您是否在參數聲明前面試過'[DefaultValue(null)]'屬性而不是'= null'?我想知道這是否會改變行爲。 –

回答

0

提供爲對象的默認值此示例將工作

public class SearchModel 
{ 
    public bool IsMarried{ get; set; } 


public SearchModel() 
    { 
    IsMarried= true; 
    } 
} 

,如果你想驗證模型

public ActionResult Index(DataFilterInput filter = null) 
     { 
     if (!ModelState.Isvalied) 
       filter = new DataFilterInput { Top = 100 }; 
      var model = new IndexModel(); 
      return View(model); 
     } 
+0

如果我使用這個視圖模型多個地方,我想在不同的行動中有不同的默認值?這個答案的問題是,它適用於任何使用默認構造函數 – TheCatWhisperer

+0

的人,您應該創建一個模型並在每次將其用作對象時使用默認構造函數自定義視圖模型。 – AlameerAshraf

+0

只能有一個默認的構造函數 – TheCatWhisperer

0

可以decare頂部nullable

public int? Top {get;set;} 

所以當沒有提供最高價值時,默認情況下將是null您可以通過使用==nullHasValue這樣

public ActionResult Index(DataFilterInput filter) 
    { 
    if (!filter.Top.HasValue) 
     filter = new DataFilterInput { Top = 100 }; 
    var model = new IndexModel(); 
    return View(model); 
    } 
+0

頂部已經是空的。這是一個有效的狀態,因爲有人可以請求關於特定實體的信息而不是頂級的任何 – TheCatWhisperer

+0

@TheCatWhisperer,那麼你應該'可以空的'所有有效的屬性,並檢查條件爲'filter.Top.HasValue && filter.property1.HasValue && filter.property2.HasValue' – Usman

+0

這不是一個可維護的解決方案。 – TheCatWhisperer