2014-07-11 32 views
1

在使用MVC 4的出租車預訂系統中,我在Home-> Index中使用局部視圖來顯示Quick Book部分。在該佈局中,我使用以下代碼來呈現局部視圖:ASP.NET MVC在局部視圖中通過ModelState.AddModelError顯示錯誤

@{Html.RenderAction("CategoryMenu", "Search");} 

的SearchController的CategoryMenu動作是:

[ChildActionOnly] 
    public ActionResult CategoryMenu() 
    { 
     var searches = new QuickSearch(); 
     return PartialView(searches); 
    } 

的快速搜索模式是:

public class QuickSearch 
{ 
    public int CatId { get; set; } 

    [DisplayName("Pickup date")] 
    [Required(ErrorMessage = "Pickup Date is required.")]  
    public string PickupDate { get; set; } 

    [DisplayName("Cab Type")] 
    [Required(ErrorMessage = "Category is required.")] 
    public int CabCategory{ get; set; } 


    public static IEnumerable<Category> Categories = new List<Category> { 
new Category { 
    CategoryId = 1, 
    Name = "Economy" 
}, 
new Category { 
    CategoryId = 2, 
    Name = "Midsize" 
}, 
/*Other categories*/ 
}; 
} 

最後,在CategoryMenu.cshtml文件的部分視圖中,我將QuickSearch模型發送給SearchController的SearchByDate操作。在SearchByDate操作中,我希望確保分揀日期不早於當前日期。我創建了一個AppHelper.CheckDate()方法來驗證需求。 但是,我無法在首頁索引中存在的分部視圖中顯示較早取件日期的錯誤消息。在SearchByDate動作,我試過如下:

if (!AppHelper.CheckDate(model.PickupDate)) 
     { 

      ModelState.AddModelError("", "Date cannot be before the current date."); 
      return PartialView("CategoryMenu"); 

     } 

然而,整個CategoryMenu視圖是越來越顯示與錯誤信息,而不是應該得到顯示在主頁索引的局部視圖的錯誤消息。任何幫助將不勝感激。

+0

您在哪裏放置了驗證摘要?父視圖。? –

+0

CategoryMenu.cshtml文件中沒有:@ Html.ValidationSummary(true) – user2693135

回答

0

這是因爲您只是在出現錯誤後顯示視圖。您的代碼是 -

if (!AppHelper.CheckDate(model.PickupDate)) 
{ 
    ModelState.AddModelError("", "Date cannot be before the current date."); 
    return PartialView("CategoryMenu"); 
} 

將此錯誤添加到ModelState是可以的。但return部分不是。您只返回視圖,這就是它顯示視圖的原因。

如果(a)您只需要顯示錯誤不是視圖,那麼只返回錯誤 -

return Content("Date cannot be before the current date.") 

(二)要顯示視圖,與錯誤,請嘗試傳遞ModelsStaterender錯誤正確旁邊的觀點 -

return PartialView("CategoryMenu", model); 

(c)如果你是顯示在父視圖中的錯誤,不希望呈現從這個局部視圖錯誤或任何東西,然後嘗試返回一個空的結果 -

return new EmptyResult(); 
+0

只要用戶使用'return RedirectToAction(「Index」,「Home」)選擇較早的日期,我就能夠顯示包含分部視圖的主頁。 ,模型);' 。這意味着用戶無法在更早的日期預訂出租車。但是,我無法顯示錯誤消息。我在SearchByDate操作中嘗試了'ModelState.AddModelError'和ViewBag.ErrorMessage。在主索引和局部視圖中,我嘗試將錯誤消息顯示爲'@ Html.ValidationSummary(true)'和'@ ViewBag.ErrorMessage;'。 – user2693135

+0

你可能想嘗試傳遞這樣的viewdata來顯示部分視圖中的錯誤 - http://stackoverflow.com/questions/1169170/pass-additional-viewdata-to-a-strongly-typed-partial-view –

+0

完成使用TempData。感謝指針。 – user2693135

相關問題