c# - returning success/failure message to view after database update -
i display status message user after update profile page indicate whether successful or not. here 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> 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 appears working me, i'm guessing there more logical way?
you should consider switching prg pattern in use case. prg stands post-redirect-get. in approach after finishing transaction (ex :updating user record), return redirect response client browser new location , browser make totally new http call load action method.
you can pass tempdata transfer success message. if there error in completing operation, may use modelstate.addmodelerrormethod add error 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 action(profiles?id=someid), need check tempdata value , display needed.
in case of error, in view(profiles), may use html.validationsummary helper method show error message added model state dictionary.
Comments
Post a Comment