0

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

3 Answers 3

3
<script type="text/javascript">
    var ViewData_a = "<%= ViewData["a"] %>";
</script>

...

<script type="text/javascript">
    $(document).ready(function() {
        if(ViewData_a) {
            $('#div1').show();
        }
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

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.