2011-10-18 57 views
0

我有一个控制器2种动作方法,MVC验证和错误处理周期

指数:

public ActionResult Index(string url) 
{ 
    // take the url as a param and do long tasks here 
    ViewBag.PageTitle = "title"; 
    ViewBag.Images = "images"; 
    // and some more view bags 
    return View(); 
} 

该索引视图包含其张贴到在同一个控制器的另一种方法的一种形式。

public ActionResult PostMessage(string msg, string imgName) 
{ 
    // save data in the db 
    // but on error I want to navigate back to the Index view but without losing data the user fielded before submit the form. 
    // Also need to pass an error message to this index view to show 
} 

如何回返回索引视图是否有出错的PostMessage的方法,也不要清除表单域,再加上示出了指定的PostMessage的方法的错误消息。

我需要知道做这种情况的最佳做法。

回答

1

最好的方法通常为您创造形式的视图模型类型。将属性添加到该模型的属性中以定义使其“错误”的内容。使您的表单使用方法如@Html.TextBoxFor各个领域。然后让你的PostMessage类获取该类型的对象,而不是直接获取消息和图像名称。然后,您可以验证模型并在模型无效时再次返回视图。

查看http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx了解此模式后面的一些代码示例。

1

你可以指定要返回视图的名称:

public ActionResult PostMessage(string msg, string imgName) 
{ 
    if (SomeErrorWhileSavingInDb) 
    { 
     // something wrong happened => we could add a modelstate error 
     // explaining the reason and return the Index view. 
     ModelState.AddModelError("key", "something very wrong happened when trying to process your request"); 
     return View("Index"); 
    } 

    // everything went fine => we can redirect 
    return RedirectToAction("Success"); 
} 
+0

和我从索引方法发送到索引视图显示,在这种情况下,它们为空的ViewBag(s)怎么样。 –

+1

@Amr ElGarhy,如果你重新显示相同的视图,你将不得不在'PostMessage'中再次设置它们。顺便说一下,你不应该使用任何ViewBag。我会建议你使用视图模型。 –

0

只是重定向到Index操作

return RedirectToAction("Index"); 

有此方法允许你传递路线值和其他信息过载。

+0

这样,他将放弃用户在输入字段中输入的所有值。有点烦人,如果你必须重新开始每次有一个服务器端错误。 –