0

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>
}
ArunPratap
  • 4,816
  • 7
  • 25
  • 43
chaeusang chen
  • 99
  • 1
  • 12
  • On which page do you want to show a message? If on the view with form then you should not use `RedirectToAction` inside `Create`. Ideally, call of this action should be asyncronious(using ALAX) and it should return your message or some other indicator of success. Then inside ajax success callback you can show the message and redirect the user to the index page. Otherwise if you want to show this message on the index page then you should use temp data and check it on the Index page, not on the view with form. – Roman Koliada Apr 24 '19 at 15:03
  • actually, it doesn't matter where the message is displayed, it can be displayed in create or index. but in my code it is displayed on the create page, if the message appears, the user will click OK on the message then redirect to index. or is there an easier way? @RomanKoliada – chaeusang chen Apr 24 '19 at 15:27
  • If you want to redirect the user only after click on the message then I'm afraid there is no other way rather then use ajax request and redirect on the client side. – Roman Koliada Apr 24 '19 at 15:31
  • What if as you said before, a successful message is made on the index page using temp data? if possible, can you tell me how to use it? @RomanKoliada – chaeusang chen Apr 24 '19 at 15:52
  • Possible duplicate of [How do I show a message before redirect](https://stackoverflow.com/questions/43997081/how-do-i-show-a-message-before-redirect) – Heretic Monkey Apr 25 '19 at 19:22

2 Answers2

0

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ParamNoRekeningSumberDana model)
{
    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();
        TempData["SuccessCreate"] = "Saved successfully";

        return RedirectToAction("Index");
   }
   else
   {
         return View(model);
   }

}

View

  @{
     if (ViewBag.SuccessCreate != null){
       <script type="text/javascript">
        var temp = '@TempData["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>
   }
MrLu
  • 376
  • 2
  • 9
0

Take a look at this question (Set Viewbag before Redirect), where they explain you should use the TempData over the Viewbag in these situations.

When you return a View, the Viewbag stil applies to the View context. But when you use a RedirectToAction, that it's actually an HTTP redirect, so .NET "clears" the ViewBag as it creates another instance to use on this new page.

You can read more about it here: https://www.c-sharpcorner.com/blogs/viewdata-vs-viewbag-vs-tempdata-in-mvc1