2017-05-31 37 views
1

在其他問題中,我已閱讀了許多有關Controller上的Create動作的信息,其中最佳做法是對GET方法執行RedirectToAction,但如果我想要顯示成功保存的消息並清除模型或提交提交併創建新的輸入類型。例如,這裏是我的代碼,是否有更好的標準兼容方式來清除創建模型?在ASP MVC中清除模型的最佳方法創建動作

[HttpPost] 
public ActionResult Create(RegisterUserViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     /* perform create action validation and operation in service and repository layers */ 
     var service = new UserManagementService(); 
     var registerUser = service.RegisterUser(model); 

     if(registerUser == ServiceStatus.Successful) 
     { 
      //Here I set the "Correctly created" message to the model 
      model.ServiceResponse = registerUser; 
      //Here I "clear" my model 
      ModelState.Clear(); 
      model = new RegisterUserViewModel(); 
      //What is the most useful suggestion is this, but here I can´t pass model data 
      //return RedirectToAction("Create"); 
     } 
    } 
    return View(model); 
} 
+2

你可以用'TempData'的留言,然後檢索它在GET方法時您重定向。 –

回答

1

你可以試試這個:

[HttpPost] 
public ActionResult Create(RegisterUserViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     /* perform create action validation and operation in service and repository layers */ 
     var service = new UserManagementService(); 
     var registerUser = service.RegisterUser(model); 

     if(registerUser == ServiceStatus.Successful) 
     { 

      //set succesfully saved message 
      TempData["Message"] = "Success Message"; 
      return RedirectToAction("Create"); 
     } 
    } 
    return View(model); 
} 
+0

如果我想發送和反對,該怎麼辦? TempData可以發送對象? –

+0

是的,您可以傳遞/發送tempdata中的對象,也可以將對象作爲參數傳遞給RedirectToAction()方法。請參閱此鏈接https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirecttoaction(v=vs.118).aspx –

相關問題