views:

83

answers:

2

Hi, I want to execute a function on loading the partial view. I have my partial view as follows. I am trying to call the function from script. But I think I can not use ViewData in my script. I don;t know proper way to use viewdata in script. Is there any way to access the viewdata inside script.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<clsAdministration>" %>
    <script language="javascript" type="text/javascript" for="window" event="onload">              
      InitializeView(ViewData["RoleErrMessage"]);  
    </script>

    <script type="text/javascript" language="Javascript">
      function InitializeView(msg) {
        if (msg.toString().length > 0) {
          alert(msg);
        }   
      }
    </script>

Thanks, Kapil

+3  A: 

If you change this line:

InitializeView(ViewData["RoleErrMessage"]);

To something like this:

InitializeView('<%=ViewData["RoleErrMessage"]%>');

It will work. The reason for this is that the script that will run is this:

InitializeView('Message');

The server side code (<%=ViewData["RoleErrMessage"]%>) will be executed at the server side and then the result will be sent to the client and your javascript will run.

Mattias Jakobsson
Even this is not working.
kapil
Then you are not doing as I suggested or you are expecting something else. What is the problem?
Mattias Jakobsson
NOw I have done something like this. But still it's not working.<script type="text/javascript" language="Javascript"> window.onload = InitializeView(); function InitializeView() { var errMessage = document.getElementById("ErrMessage"); if (errMessage != null) { if (errMessage.toString().length > 0) {alert(errMessage);}}}</script>
kapil
Why are you doing it like that? Why not just do it as easy as possible: window.onload = function() { var message = '<%=ViewData["RoleErrMessage"]%>';if(message.length > 0) { alert(message); } };
Mattias Jakobsson
A: 

Kapil, perhaps the script is running before the document is fully loaded.

Can you try running it when the document is loaded. Unsure how to do it in javascript anymore but in jQuery you'd write;

$('document').ready(function(){InitializeView('<%=ViewData["RoleErrMessage"]%>'); });

I think you still need to do the code that @Mattias suggested but I may be wrong.

The above is totally untested so you may need to adjust a little.

griegs