javascript 表单提交后的 ASP.net MVC 成功警报

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23505985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:00:47  来源:igfitidea点击:

ASP.net MVC Success Alert After Form submit

javascriptjqueryasp.net-mvcasp.net-mvc-4

提问by Chlebta

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:

我想在提交表单和操作成功后显示成功警报弹出窗口或警报消息
在这个例子中我想显示“成功添加” 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:

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 ?

我应该添加什么来做到这一点?

回答by Anderson Matos

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.

执行此操作的最常见方法之一(也是我目前使用的非常成功的方法)是接收您需要接收的内容并返回带有状态和/或错误消息的 JSON 对象,这将在您的视图中被某些脚本使用。

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.

然而,这将迫使你在视图模型中加载一些额外的东西,比如一个额外的<script>标签或一些额外的<div>标签,并每次都检查。

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-useris just wasting bothyours andyour end-users' link.

IMHO,返回一个视图或局部视图仅显示一个消息给最终用户时只是浪费您的最终用户的链接。

回答by Ehsan Sajjad

I used to make Ajax Formand in the OnSuccessfucntion i show message :

我曾经制作Ajax 表单,并在OnSuccess功能中显示消息:

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

回答by JulioCT

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

我有办法做到这一点,使用 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 :)

最后,您将 JavaScript 与 MVC ViewBag 混合使用 :)