Lefteris Gkinis
Lefteris Gkinis

Reputation: 1259

Calling a Javascript in my razor page from a controller in MVC4

In my controller I have this function:

Function AppError() As ActionResult
        Dim myScript As Object = "popup(" + Properties.postError + ")"
        Return RedirectToAction("main", myScript)
    End Function

With this function I want to call my razor page where I have a Javascript named popup whith a parameter Properties.postError.
My script is:

<script type="text/javascript">
    var errMsg;
    function popup(msg) {
        errMsg = msg;
        window.alert(errMsg);
        window.window.focus();
        if (window.confirm)
            errmsg = '';
        msg = '';
    }
</script>

What I need is to popup the error message.
I follow the programm thru my debugger and I saw that it goes to my page.
But no error message window raise up.
I have already search in the web for this option without any success.
Is someone to assist me on this issue?

ADDITION - 16/2/19 12:50
what I have done so far is the following:

Function CBError() As ActionResult
        Dim myScript As Object = "popup(" + Properties.postError + ")"
        ViewData.Add(New KeyValuePair(Of String, Object)("ScriptName", myScript))
        Return View("main", myScript)
    End Function

As we can see I've change the function by addiding the ViewData
I Add a value pair arguments 1) the name 2) the value
The action of addition it works just fine and the dictionery receive it.
I my script (which is in my reazor page) I put the following:

<script type="text/javascript">
   var vd = @ViewData.Item(0);
       function popup(msg) {
            var errMsg;
        errMsg = msg;
        window.alert(errMsg);
        window.window.focus();
        if (window.confirm)
            errmsg = '';
        msg = '';
        //{ window.location.href = "/" }
    }
</script>

When I stop (with the bebugger) in the instruction var vd = @ViewData.Item(0); I see that the ViewData is complitely empty. No values no nothing.
I also add this window.onload = @Html.Raw(ViewBag.MyScript);
And in debugger threw me an error

"Uncaught SyntaxError: Unexpected token ;"

Is there somone to instruct me why that happen?

ADDITION - 16/2/19 20:00
New version of function and Script

Function CBError() As ActionResult
        Dim myScript As Object = Properties.postError
        ViewData.Add(New KeyValuePair(Of String, Object)("Message", myScript))
        Return View("main")
    End Function<br/>

<script type="text/javascript">
  $(document).ready(function (){
  alert("@ViewData.Values(0)");
  });
</script>

With this version I put the message value to the ViewData
But when the program comes to the point of script then all the ViwData is empty.
No Values no Keys no nothing.
It seems somewhere in the middle it lose all the data

FINAL UPDATE 17/2/19 11:13
The problem has been solved ... but not by the way we are wearing.
It was solved in an extremely simple way.
What we were asking for was to get the error message on the page we are in. From any point of the code.
So I followed the method of rendering the message to property and I read this message from the page with the following Javascript.
The function is:

Function CodePage_Error() As ActionResult
        Return View("main")
    End Function

End the Javascript is:

<script type="text/javascript">
    $(document).ready(function () {
        if ("@Properties.InnerError" !== "") {
            var msg = "@Properties.InnerError";
            window.alert(msg);
        } else {
            return false;
        }

}); The Javascript is placed in the mainLayout.vbhtml file

Generally speaking, it turned out that the transfer method from the controller to the page is not possible in the MVC4 environment

Upvotes: 1

Views: 636

Answers (2)

kingtreelo
kingtreelo

Reputation: 251

You could pass the error message to the page via Viewbag, and then put the pop up script inside the document ready javascript function to check the message and display the error if required.

Controller:

public IActionResult Index()
    {
        ViewBag.Message = "this is your message";
        return View();
    }

View:

<script type="text/javascript">
$(document).ready(function (){
alert("@ViewBag.Message");
});

Upvotes: 1

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

I think passing JS code through RedirectToAction route value parameter is not a good idea because some special characters will be encoded. You should use either ViewBag or viewmodel properties and pass the script to view in unencoded state.

Here is an example setup:

1) Use ViewBag or a viewmodel property to contain the script you want to execute in the view.

Public Function AppError() As ActionResult
    ' define Properties.postError here

    Dim myScript As String = "popup(" + Properties.postError + ")"
    ViewBag.MyScript = myScript

    Return View()
End Function

2) Use an event handler e.g. window.onload assigned with @Html.Raw() from ViewBag or viewmodel property to pass unencoded function call inside <script> tag. The event handling must be placed outside function block.

<script type="text/javascript">
    var errMsg;
    function popup(msg) {
        errMsg = msg;
        window.alert(errMsg);
        window.window.focus();
        if (window.confirm)
            errmsg = '';
        msg = '';
    }

    // the popup will be called here
    window.onload = @Html.Raw(ViewBag.MyScript)
</script>

Note that window.onload will pop up the message after the view is loaded, if you want to pop up the message in another event use any desired event handler instead (also check list of available JS DOM events).

Upvotes: 1

Related Questions