0

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 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Then you are not doing as I suggested or you are expecting something else. What is the problem?
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>
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); } };
0

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.

Comments

0

It can be done with the following code, which I've just tested.

var variable_X=('@ViewData["pubId"]');

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.