简体   繁体   中英

ASP.net MVC Success Alert After Form submit

I want to display success Alert pop-up or alert message after form submited and action succeded
In this example I want to show "successfully add" : Create Action :

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(TAUX taux)
    {
        if (ModelState.IsValid)
        {
            db.TAUX.Add(taux);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.CAT_ID = new SelectList(db.CATEGORIE, "CAT_ID", "LIBELLE", taux.CAT_ID);
        ViewBag.C_GARANT = new SelectList(db.GARANTIE, "C_GARANT", "LIB_ABREGE", taux.C_GARANT);
        return PartialView("_Create", taux);
    }

Index Action :

public ActionResult Index()
        {
            var taux = db.TAUX.Include(t => t.CATEGORIE).Include(t => t.GARANTIE);
            return View(taux.ToList());
        }

What should I add to do this ?

It's possible, for sure, but implementation details might change from technologies and app structure.

One of the most common ways for doing this (and the one I'm currently using with great success) is to receive whater-you-need-to-receive and return a JSON object with the status and/or error message, which will be used by some script on your view.

For example:

[Route(""), HttpPost]
public JsonResult DoSomethingOnTheServer(DoSomethingViewModel vm)
{
   try
   {
      if (DoSomething(vm)) return Success();
      else return Error("The server wasn't able to do something right now.");
   }
   catch (Exception err)
   {
      return Error(err.Message);
   }
}

public JsonResult Success() { return Json(new { Success = true, Message = "" }); }
public JsonResult Error(string message) { return Json(new { Success = false, Message = message }); }

This way, you can do something like:

<script>
   $.ajax({
      url: "/",
      method: "POST",
      data: getMyData(),

      success: function(json) {
         if (json.Success) {
            alert("Wow, everything was fine!");
         } else {
            alert(json.Message);
         }
      },

      // This will be trigered whenever your ajax call fails (broken ISP link, etc).
      error: function() {
         alert("Something went wrong. Maybe the server is offline?");
      }
   });
</script>

Being honest with you, it's possible to submit the form (regular submit, I mean) and on the page refresh, display whatever you want.

This will, however, force you to load something extra with your view model, like an extra <script> tag or some extra <div> tags and to check for that every time.

From a usability/design point-of-view, it's a no-go. Avoid page refresh whenever possible because they give a feeling for the user that the app is either going away or that he/she is now moving outsinde the app.

Also, from a performance point-of-view, "full round-trips" to the server, consisting of sending the form data and retrieving a whole new page (with the whole layout, scripts, razor rendering/parse and all) is a massive problem just to show "success/fail" for the end-user so, again: avoid it whenever possible.

IMHO, returning either a view or a partial view only to display a message to the end-user is just wasting both yours and your end-users' link.

I used to make Ajax Form and in the OnSuccess fucntion i show message :

@using (Ajax.BeginForm("Edit1", "Availability", new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.InsertBefore, UpdateTargetId = "formAddAvailabilityContainer", OnSuccess = "AddAvailabilitySuccess" }, new { @class = "AjaxForm", @id = "formAvailability_" + Model.Id }))
    {
        @Html.ValidationSummary(true)




        @Html.HiddenFor(model => model.Id)
        @Html.HiddenFor(model => model.UserId)

        @Html.EditorFor(model => model.StartTime)
        @Html.MyValidationMessageFor(model => model.StartTime)

        @Html.EditorFor(model => model.EndTime)
        @Html.MyValidationMessageFor(model => model.EndTime)

        @Html.EditorFor(model => model.RecurrenceFreq)
        @Html.MyValidationMessageFor(model => model.RecurrenceFreq)



      @Html.TextBoxFor(model => model.EndsAfterValue, new {id="txtBoxEndsAfterValue" })
     @Html.MyValidationMessageFor(model => model.EndsAfterValue)



    @Html.EditorFor(model => model.EndsByDate)


    <input type="submit" class="btn btn-primary" value="Save" id="btnsubmit" />
   <input type="button" class="btn btn-primary btnCancelAvailability" id="0" value="Cancel">


    }


 <script>

    function AddAvailabilitySuccess()
    {

    alert("Record updated successfully!");

    }

    </script>

I have a way to do this, using the ViewBag.

In your controller you must add:

if (ModelState.IsValid)
        {
            db.TAUX.Add(taux);
            db.SaveChanges();
            ViewBag.SuccessMsg = "successfully added";
            return RedirectToAction("Index");
        }

Then in the Index view:

@{
    var message = ViewBag.SuccessMsg;
}

<script type="text/javascript">
    var message = '@message';
    if(message){
        alert(message);
    }
</script>

in the end you use JavaScript mixed with the MVC ViewBag :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM