2

I need to return an alert message from a action in a controller in asp.net mvc, is it possible ? I tried getting the page instance and calling the RegisterJavaScript funtion but the page instance is null always because I read that its the MVC handler now not the page handler. I know I can return a javscript result but my action is doing a redirect to a different url just before redirecting I need to show the message. Could somebody help me ? I cannot use a viewbag or viewdata because its on a post that I need to show the message and its not going back to the view once post is done. So there is no way to check for the variable value and show the message.

  public ActionResult RedirectToURL(ObjectData obj)
    {                      

        if (ModelState.IsValid())
        {
            process code here                
        }
        else
        {
           ModelState.AddModelError("Error", "Fill in the required fields");
           return View("TestView", ObjectData);
        }     

        //Post data to the URL.
        //Prepare Data to Post

        //Need JavaScript call here....            

        return this.RedirectAndPost(Url, dataToPost);
    }
3
  • If you need to show the client a message before or during post, why not just have your submit button trigger some javascript that shows the message then continue with your post? Commented Apr 13, 2018 at 15:04
  • 1
    You can't show an alert from server code because the code is on the server and the JavaScript is client side code. I am not 100% clear on the flow of your code, if you could explain why the redirect is happening etc. it might be possible to offer another solution Commented Apr 13, 2018 at 15:05
  • You may be better off using JavaScript to Ajax back to the server, then reading a status code so you can have JavaScript redirect to said location, then have the initial controller index populate the model accordingly. Commented Apr 13, 2018 at 15:27

1 Answer 1

2

You have to use the viewbag for transferred the message at view.

Also you need to put the condition that viewbag value is not null so it will not show alert when their is no message.

  @if(ViewBag.message!=null)
       {
           <script type="text/javascript">
          alert( "@(ViewBag.AlertMessage)");
          </script>
       }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.