views:

384

answers:

1

I'd like to add a click handler for a button using jQuery, but the handler needs to reference data supplied by the controller. Is there a way to access ViewData in a script block in ASP.NET MVC? Or do I need to construct the script in the controller?

+2  A: 

If the script block is within the ASP.NET page then you can reference it...

e.g:

<script type="text/javascript">
 jQuery(document).ready(function() {
  jQuery('#group-edit-form').validate({
   rules: {
    title: {
     required: true,
     remote: '<%=Url.Action("ValidateGroupName", new { id = ViewData["GroupId"] }) %>?parentId=' + getParentId()
    }
   },
   messages: {
    title: {
     required: getMessage (7002),
     remote: '<%= ((MessagingModel)ViewData["Messages"]).GetMessage (9001) %>'
    }
   }
  })

 });
</script>

When the page is processed by the runtime engine, everything within the <% ... %> blocks is evaluated, regardless of it's location in the page.

Kieron
Do you get Intellisense when you do this?
tvanfosson
Unfortunately no, VS reads it as part of the string, at least in the sample above ):
Kieron
VS 2008 Gives you intellisense on your aspx pages.
Darryl Braaten
I'm not getting intellisense either inside a script block or inside an HTML tag.
tvanfosson
I don't get Intellisense when its inside a script block. For scenarios like above ill create the tag outside the script block for intellisense and then copy'n'paste it into the script tag area. Kinda clunky.
Todd Smith