2015-02-09 36 views
0

我有2種方法 - GET和POST。 GET方法填充表單,POST方法向DB添加記錄。有用。但有時POST方法會得到一個錯誤(無效的數據,無法在客戶端等檢查),我再次調用GET方法。方法之間傳遞錯誤

GET方法:

public ActionResult VacancyForm(int? ID, VacancyFormViewModel model) 
{ 
    if (model == null) 
     model = new VacancyFormViewModel(); 

POST方法:

[HttpPost] 
public ActionResult VacancyForm(VacancyFormViewModel model) 
{ 
    if (surgeonSelected == null) // error case 
    { 
     return VacancyForm(null, model); 
    } 

的問題 - 如何通過從後所有的錯誤得到?

+0

你不知道!將錯誤添加到'ModelState'並返回視圖 - ModelState.AddModelError(string.Empty,「your error message」);返回View(模型);' - 不要調用GET方法 – 2015-02-09 22:19:22

回答

0

可以使用的ModelState的AddModelError方法把它們添加服務器端在你的控制器如下:

[HttpPost] 
public ActionResult VacancyForm(VacancyFormViewModel model) 
{ 

    if (surgeonSelected == null) // error case 
    { 
     ModelState.AddModelError("SurgeonSelected ", "An error has occurred"); 
     return VacancyForm(model); 
    } 
} 

這可以通過以下方式顯示出來:

@Html.ValidationMessage("SurgeonSelected ") 

如果使用強類型的意見你可以使用:

@Html.ValidationMessageFor(m => m.SurgeonSelected) 
0

你可以通過它作爲參數:

public ActionResult VacancyForm(int? ID, VacancyFormViewModel model, string errorMessage = null) 
    { 
     if(errorMessage != null) 
      ModeState.AddModelError("", errorMessage); 

    } 

[HttpPost] 
public ActionResult VacancyForm(VacancyFormViewModel model) 
{ 

    if (surgeonSelected == null) // error case 
    { 
     string error = "You error message"; 
     return VacancyForm(null, model, error); 
    } 
}