I want to display a successful message to the user after the data has been saved. I create a Viewbag in the controller and call it in view. After the save button is clicked the data is saved but the success message does not appear. it immediately redirects to the index page. Below is my code, thanks
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ParamNoRekeningSumberDana model)
{
ViewBag.SuccessCreate = "";
if (ModelState.IsValid)
{
ParamNoRekeningSumberDana newrecord = new ParamNoRekeningSumberDana();
newrecord.ID = Guid.NewGuid();
newrecord.AccountNo = model.AccountNo;
newrecord.CreatedBy = Session["UserName"].ToString();
db.ParamNoRekeningSumberDanas.Add(newrecord);
db.SaveChanges();
ViewBag.SuccessCreate = "Saved successfully";
return RedirectToAction("Index");
}
else{
return View(model);
}
}
View
@{
if (ViewBag.SuccessCreate != null){
<script type="text/javascript">
var temp = @Html.Raw(Json.Encode(ViewBag.SuccessCreate));
alert(temp);
</script>
}
}
@using (Html.BeginForm())
{
<div class="form-group">
@Html.LabelFor(model => model.AccountNo, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.AccountNo, (List<SelectListItem>)ViewBag.AccountNos, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.AccountNo, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}