验证消息在MVC中的POST-Redirect-GET中丢失

时间:2009-06-30 10:43:31

标签: asp.net-mvc

我有一个带动作索引的ProductController(加载一个空白表单)。表单还将自身作为复杂表单发布,下拉列表等表单元素显示已发布的值 代码如下

 public ActionResult Index()
    {
        int id;
        id = Convert.ToInt32(Request.Form["ddlLendingType"]);
        if (id == 0)
            id = 1;
        ProductCommonViewModel viewData = new ProductCommonViewModel(_prodRepository.Method1(),_prodRepository.Method2())
        return View(viewData);
    }

当我单击表单中的提交时,它会保存产品,如果失败,则应显示验证错误消息。

 [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Save(FormCollection fc)
    { 
        Product product = new Product();
        try
        {
           ...fill out all properties from form collection
            _prodRepository.SaveProduct(product);

            return RedirectToAction("Index", "Product");
        }
        catch (Exception ex)
        {
            TempData["Message"] = "An Error Occured while saving the product!";
            Validation.UpdateModelStateWithRuleViolation(product, ViewData.ModelState);
            // WHEN I call redirect to action Index on this view I can see the TempData variable but I cannot see validation summary and individual validation messages.How do I persist the msgs across requests?
        }

    } 

辅助方法定义如下:

public static void UpdateModelStateWithRuleViolation(IRuleEntity entity, ModelStateDictionary dictModel)
    {
        List<RuleViolation> violations = entity.GetRuleViolations();

        foreach (var item in violations)
        {
            dictModel.AddModelError(item.PropertyName, item.ErrorMessage);
        }
    }

2 个答案:

答案 0 :(得分:2)

也将modelstate传递给tempdata。

顺便说一下,而不是这个:

 public ActionResult Index()
    {
        int id; //and here You could join declaration with assignment
        id = Convert.ToInt32(Request.Form["ddlLendingType"]);

你可以这样做:

 public ActionResult Index(int ddlLendingType)
        {

使用FormCollection是一种不应该使用的错误做法。对于极端情况 - 创建自定义模型绑定器(CodeCampServer具有相当不错的绑定机制)或操作过滤器(Kigg的源)。

答案 1 :(得分:1)

我遇到了在多个请求中保留TempData的问题,我做了以下操作,为每个重定向操作刷新TempData:

protected override RedirectToRouteResult RedirectToAction(string actionName, 
    string controllerName, System.Web.Routing.RouteValueDictionary routeValues)
{
    TempData["Notice"] = TempData["Notice"];
    TempData["Error"] = TempData["Error"];
    TempData["Warning"] = TempData["Warning"];
    return base.RedirectToAction(actionName, controllerName, routeValues);
}