Mike
Mike

Reputation: 83

How to show Message Box in MVC ASP.NET without return View()

i'm new here in stackoverflow and also new to asp.net i would like to ask how to show message box in mvc asp.net. This is my code, but it will return NullReferenceException. Thanks for your help.`

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult myfunction(MyViewModels myModel)
    {
        System.Web.UI.ScriptManager script_manager = new System.Web.UI.ScriptManager();

        if (ModelState.IsValid) {
            createRequest(myModel);
            script_manager.Page.ClientScript.RegisterStartupScript(this.GetType(), "showMyMessage", "ShowMessage('Requested Successfully.');", true);
            return RedirectToAction("GeneratePDF", "Forms", myModel);   
        }
        else
        {
            script_manager.Page.ClientScript.RegisterStartupScript(this.GetType(), "showMyMessage", "ShowMessage('Requested failed.');", true);
            return RedirectToAction("Index");
        }
    }`

Upvotes: 2

Views: 18967

Answers (1)

Karthik Elumalai
Karthik Elumalai

Reputation: 1612

There are different ways to do the same thing, I have added three different ways and you can use, whatever required for you in different times.

Way 1: [Recommended for your requirement without return view()]

public ContentResult HR_COE()
       {


           return Content("<script language='javascript' type='text/javascript'>alert     ('Requested Successfully ');</script>");
       }

Official definition for content result class:

Represents a user-defined content type that is the result of an action method.

Source: https://msdn.microsoft.com/en-us/library/system.web.mvc.contentresult(v=vs.118).aspx

Other useful examples if required: http://www.c-sharpcorner.com/UploadFile/db2972/content-result-in-controller-sample-in-mvc-day-9/

https://www.aspsnippets.com/Articles/ASPNet-MVC-ContentResult-Example-Return-String-Content-from-Controller-to-View-in-ASPNet-MVC.aspx

Other ways:

Way 2: Controller Code:

public ActionResult HR_COE()
       {
           TempData["testmsg"] = "<script>alert('Requested Successfully ');</script>";
           return View();
       }

View Code:

@{
    ViewBag.Title = "HR_COE";
}

<h2>HR_COE</h2>

@if (TempData["testmsg"] != null)
{
   @Html.Raw(TempData["testmsg"]) 
}

Way 3: Controller code:

public ActionResult HR_COE()
      {
          TempData["testmsg"] = " Requested Successfully ";
          return View();

      }

View code:

@{
    ViewBag.Title = "HR_COE_Without using raw";
}

<h2>HR_COE Without using raw</h2>

   @if( TempData["testmsg"] != null)
   {
<script type="text/javascript">
       alert("@TempData["testmsg"]");
</script>
   }

I have used all the three ways personally and I got the output as expected. So Hope it will be surely helpful for you.

Kindly let me know your thoughts or feedbacks

Thanks Karthik

Upvotes: 9

Related Questions