PixelPaul PixelPaul - 28 days ago 4
ASP.NET (C#) Question

returning success/failure message to view after database update

I would like to display a status message to a user after they update a profile page to indicate whether it was successful or not. Here is what I have:

Controller

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


Database Call

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>
}


While this appears to be working for me, I'm guessing there is a more logical way?

Answer

You should really consider switching to the PRG Pattern in this use case. PRG stands for POST-REDIRECT-GET. In this approach after successfully finishing a transaction (ex :Updating user record), you return a redirect response to the client browser with the new location and browser will make a totally new http get call to load that GET action method.

You can pass TempData to transfer the success message. If there was any error in successfully completing the operation, you may use the ModelState.AddModelErrorMethod to add an error to the model state dictionary.

[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);
    }
}

Now in your GET action(Profiles?id=someId), you basically need to check the TempData value and display it as needed.

In the case of an error, in the view(Profiles), you may use the Html.ValidationSummary helper method to show the error message we added to the model state dictionary.