2016-11-11 59 views
0

我想在用户更新配置文件页面以指示其是否成功后向用户显示状态消息。以下是我有:在数据库更新后返回成功/失败消息以查看

控制器

[HttpPost] 
public ActionResult Profiles(UserProfile model) 
{ 
    try 
    { 
     _userRepository.UpdateUserProfile(model); 
     ViewBag.Message = "Success"; 
    } 
    catch 
    { 
     ViewBag.Message = "Failure"; 
    } 
    return View(); 
} 

数据库调用

public void UpdateUserProfile(UserProfile user) 
{ 
    using (var connection = new SqlConnection(SQLSettings.GetConnectionString())) 
    { 
     var p = new DynamicParameters(); 
     p.Add("@Id", user.Id); 
     p.Add("@City", user.City); 
     p.Add("@State", user.State); 
     connection.Execute("UpdateUserProfile", p, commandType: CommandType.StoredProcedure); 
    } 
} 

VIEW

@if (ViewBag.Message == "Success") 
{ 
    <div class="alert alert-success"><strong><span class="glyphicon glyphicon-check"></span> Your profile has been updated.</strong></div> 
} 
@if (ViewBag.Message == "Failure") 
{ 
    <div class="alert alert-danger"><span class="glyphicon glyphicon-alert"></span><strong> Error, please try again.</strong></div> 
} 

得到控制而这似乎是为我工作,我猜是有一个更合乎逻辑的方法?

+0

你是什么意思关于“更合乎逻辑的方式”?在这里看起来你的代码没有错。 –

+2

你应该真的把模型传递给你的视图,而不是使用ViewBag。 – DavidG

+0

我想我不确定try-catch应该在控制器中还是在调用db调用的实际方法中,并从那里返回成功或错误? – PixelPaul

回答

1

在这个用例中你应该考虑切换到PRG模式。 PRG代表POST - REDIRECT - GET。在成功完成一个事务(例如:更新用户记录)之后,在此方法中,您将返回一个重定向响应到带有新位置的客户端浏览器,浏览器将创建一个全新的http get调用来加载该GET操作方法。

您可以通过TempData传输成功消息。如果成功完成操作时出现任何错误,您可以使用ModelState.AddModelErrorMethod向模型状态字典添加错误。

[HttpPost] 
public ActionResult Profiles(UserProfile model) 
{ 
    try 
    { 
     _userRepository.UpdateUserProfile(model); 
     TempData["Message"] = "Success"; 
     return RedirectToAction("Profiles",new { id= model.Id }); 
    } 
    catch 
    { 
     ModelState.AddModelError(string.Empty,"Some error happened"); 
     return View(model); 
    } 
} 

现在在您的GET操作(Profiles?id = someId)中,您基本上需要检查TempData值并根据需要显示它。

如果出现错误,在视图(Profiles)中,可以使用Html.ValidationSummary辅助方法来显示我们添加到模型状态字典中的错误消息。

+1

谢谢你这么详细的解释,这是最有帮助的。 – PixelPaul

相关问题