我想在用户更新配置文件页面以指示其是否成功后向用户显示状态消息。以下是我有:在数据库更新后返回成功/失败消息以查看
控制器
[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>
}
得到控制而这似乎是为我工作,我猜是有一个更合乎逻辑的方法?
你是什么意思关于“更合乎逻辑的方式”?在这里看起来你的代码没有错。 –
你应该真的把模型传递给你的视图,而不是使用ViewBag。 – DavidG
我想我不确定try-catch应该在控制器中还是在调用db调用的实际方法中,并从那里返回成功或错误? – PixelPaul