ASP.NET MVC在局部视图中通过ModelState.AddModelError显示错误

时间:2014-07-11 13:41:55

标签: asp.net-mvc

在使用MVC 4的出租车预订系统中,我在Home-> Index中使用局部视图来显示Quick Book部分。在布局中,我使用以下代码呈现局部视图:

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

SearchController的CategoryMenu操作是:

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

QuickSearch模型是:

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视图将显示错误消息,而不是应显示在Home Index的部分视图中的错误消息。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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.")

(b)您希望显示包含错误的视图,尝试将错误与ModelsState一起正确传递给render -

return PartialView("CategoryMenu", model);

(c)如果您在父视图中显示错误并且不想从此部分视图中呈现错误或任何内容,则尝试返回空结果 -

return new EmptyResult();