Pergunta

Eu estou tentando criar uma grade ajax simples que me permite adicionar e linhas remover e também editar algumas das colunas e têm outras colunas calculadas diretamente com base na entrada nos outros. Eu pensei que esta seria uma boa oppurtunity para brincar com asp.net ajax 4.0 e os modelos cliente. Ele funciona muito bem, mas eu não consigo encontrar uma maneira de vincular os meus dados JSON para um. Como posso fazer isso?

A aparência normais modelo como este

<div id="authorsTemplate" style="visibility:hidden;display:none;"> 
    <ul> 
        <li>First Name: {{ FirstName }}</li> 
        <li>Last Name: {{LastName}}</li> 
        <li>Url: <a href="{{Url}}">{{Url}}</a></li> 
    </ul> 
</div> 

Como eu iria usar os dados ligamento sintaxe com uma lista suspensa

<select id="">
  <option value="1">1</option>
  <option value="2">2</option>
</select>

EDIT: Se o select tag tinha um atributo de valor a solução óbvia seria. Edit2: A sintaxe abaixo foi realmente a solução, Thx Roatin, eu não tinha idéia da escolha realmente tinha um atributo de valor.

<select id="" value="{binding nr}">
    <option value="1">1</option>
    <option value="2">2</option>
</select>

Eu poderia talvez usar javascript personalizado para definir a opção selecionada, mas o ponto é uma ligação em directo ao meu objeto JSON da mesma forma que se ligam ao valor de uma marca de entrada

Foi útil?

Solução

I do not want to populate the dropdown, it is already populated. I want to be able to use the client template binding syntax to get the value from my json object and set the selected element.

In fact, select DOM elements do have a value property (but not exposed as an attribute in the markup). Setting it is equivalent to (and faster than) iterating the child <option>s and setting the selectedIndex to the found option index of the option that has a matching value.

Anyway, here's how to bind to it directly with Sys.Binding (complete test case):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">.sys-template {display:none}</style>
    <script src="MicrosoftAjax.debug.js"></script>
    <script src="MicrosoftAjaxTemplates.debug.js"></script>

    <script type="text/javascript">
    var dataItem = { Foo: '3' };
    function pageLoad()
    {
        $create(Sys.Binding, {
            target: $get("list"),
            targetProperty: 'value',
            source: dataItem,
            path: 'Foo',
            mode: Sys.BindingMode.twoWay
        });
    }
    </script>
</head>
<body>
  <select id="list">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
  </select>
</body>
</html>

Here is how to do the same thing declaratively, if you prefer:

<body xmlns:sys="javascript:Sys"
      xmlns:binding="javascript:Sys.Binding"
      sys:activate="*">

  <select id="list"
    sys:attach="binding"
    binding:target="{{ $get('list') }}"
    binding:targetproperty="value"
    binding:source="{{ dataItem }}"
    binding:path="Foo">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
  </select>

(and of course get rid of the pageLoad JavaScript stuff...)

Both examples set up two-way binding to the dataItem object. You can see when the page loads, the third <option> is selected as that is the option with a value matching dataItem.Foo. When you select a different item from the drop-down, dataItem.Foo updates with the new value selected.

Hope that helps!

Outras dicas

I have not actually tried this but it looks like any of these three links blog post could help. All the examples show binding to lists of data. Maybe something like this:

* Sample not tested my VS 2010 comp is busted and is closely derived from the third link *

var sampleData = [
    { Value: "1", Text: "1" },
    { Value: "2", Text: "2" },
];
var select = "1";

<select id="list" class="sys-template" 
    sys:attach="dataview" 
    dataview:data="{{ sampleData }}">
    <option value="{{ Value }}">{{ Text }}</option>
</select>

Then to select the value you want (done the brute force way)

var list = document.getElementById( "list");
foreach ( var option in list.options)
{
    if( option.value == select)
    {
        option.selected = true;
        break;
    }
}

Or tweak the template to include a binding for a 'selected' option. ( Again not tested, you might not be able to perform Selected === true)

var sampleData = [
    { Value: "1", Text: "1", Selected: true },
    { Value: "2", Text: "2" },
];
var select = "1";

<select id="list" class="sys-template" 
    sys:attach="dataview" 
    dataview:data="{{ sampleData }}">
    <option value="{{ Value }}" selected="{{ Selected === true }}">{{ Text }}</option>
</select>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top