do you write your JavaScript in a ASP.NET MVC view … or in a separate JavaScript file?

后端 未结 6 1717
深忆病人
深忆病人 2020-12-07 11:24

Trying to improve my coding styles I\'ve tried different solutions but I can\'t figure out what is the best.
I\'ve started putting JavaScript inside my views but I don\'

6条回答
  •  难免孤独
    2020-12-07 11:58

    Here's my methods on ASP.NET MVC3 to complete the @weirdlover answer, one thing he's missing is the JSON encoding which is quite important when you want to safely inject data in js.

    If the data is not too big and can be logically attached to a DOM element, I use one (or several) data-attribute (don't require a jQuery plugin and leave the css class pretty) and a css class to find the elements from jQuery.

    Stupid example:

    HTML:

    COFFEESCRIPT:

    class TextWidget
      constructor: (@element) ->
        @el = $ @element
        @options = @el.data 'options'
        @input = @el.find 'input'
        @input.change @update
    
      update: =>
         value = @input.val()
         $.post @options.url, 
           value: value
           , -> alert 'text saved'
    
    $ ->
      new TextWidget element for element in $('.text-widget').get()
    

    A little gotcha with Json.Encode and jQuery.data: if you use it on a simple string, you will get a quoted string in javascript: $().data('strattribute') == ' "hello" '. Just use Html.Encode in that case.

    Anyway I prefer to use a single attibute with an anonymous object I build in the controller, it's easier to maintain: data-options="@Json.Encode(Model.Options)".

    If there is a lot of data, like a list of objects I will turn to ViewModels for knockoutjs, I use a

提交回复
热议问题