views:

108

answers:

3

I am new to mvc and jquery In my controller I have ViewData["a"]="true"; I want to access the viewdata object in jquery <% if(ViewData["a"] == "true")%> { $('#div1').show(); } The above jquery doesn't work for me Can someone please shed light on this. Thanks in advance

A: 

You can't access your ViewData in this manner. You'll need to do something like putting the value into say a hidden field and then checking that.

if ($('.HdnFieldClassName').val() == "true")
{
  $('#div1').show();
}

Or something like that.

Unsure whether you can do something like

if ( '<%= ViewData["a"] %>' == "true"

I don't know about other people but I'm not a huge fan of using control names in jQuery. I much prefer to use the class name to grab a control.

<input type='text' class="jQueryMyTextBox" id='MyTextBox'>

$('.jQueryMyTextBox').val()

It just means that if the control name changes that your code still works and you can now share the code between forms etc.

griegs
+2  A: 
<script type="text/javascript">
    var ViewData_a = "<%= ViewData["a"] %>";
</script>

...

<script type="text/javascript">
    $(document).ready(function() {
        if(ViewData_a) {
            $('#div1').show();
        }
</script>
eu-ge-ne
A: 

While you're at it, consider using JSTL/EL instead of scriptlets.

So...

<%= ViewData["a"] %>

becomes...

<c:out value="${ViewData.a}"/>

JSTL/EL often gives you some things for free. Like in this example, the value of ViewData["a"] will be entity-encoded automatically.

Drew Wills