Display popup confirmation message with MVC C# after postback

大憨熊 提交于 2019-12-06 03:26:33

问题


Using MVC Framework with C# coding. The views are written in standard HTML code. I require a confirmation message saying "Your message has been sent" once the user clicks the submit button

Here is the controller:

public ActionResult Index(ContactViewModel contactVM){
        if (!ModelState.IsValid)
        {
            string url = Request.UrlReferrer.AbsolutePath+ "#contact";

            return View();
        }
        else
        {
            var contact = new Contact
            {
                Name = contactVM.Name,
                Email = contactVM.Email,
                Subject = contactVM.Subject,
                Message = contactVM.Message
            };
            new Email().Send(contact);
            return RedirectToAction("Index");
        }

Here is the View:

<input type="submit" class="submit_btn left" name="Submit" id="submit" value="Submit"/>
<input type="reset" class="submit_btn right" name="Reset" id="reset" value="Reset" />

Kindly assist.


回答1:


Instead of RedirectToAction(), return View :

    new Email().Send(contact);

    ViewBag.Message = "Message Sent"; 

    return View();

In View:

@if(ViewBag.Message != null)
{
<script>

$(document).ready(function(){

alert('@ViewBag.Message');

});

</script>

}



回答2:


Add Inside controller

        ViewBag.IsEmailSent=true;



public ActionResult Index(ContactViewModel contactVM){
            if (!ModelState.IsValid)
            {
                string url = Request.UrlReferrer.AbsolutePath+ "#contact";

                return View();
            }
            else
            {
                var contact = new Contact
                {
                    Name = contactVM.Name,
                    Email = contactVM.Email,
                    Subject = contactVM.Subject,
                    Message = contactVM.Message
                };
                new Email().Send(contact);
                ViewBag.IsEmailSent=true;
                return RedirectToAction("Index");
            }

Index.cshtml page

   @if(ViewBag.IsEmailSent)
    {
    <script>
$(function(){
     $("#successModal").modal('show'); });
    </script>
    }



回答3:


Change the result (from RedirectToAction("Index")) to a view that provides the confirmation.

If you don't want to have something that's mostly a copy of an existing page (like Index) then pass an object containing a ShowConfirmation flag, and in the index view have some logic to show the confirmation if that flag is set.



来源:https://stackoverflow.com/questions/23591266/display-popup-confirmation-message-with-mvc-c-sharp-after-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!