我可以将对象分配到下拉列表的值吗?

时间:2011-09-12 02:08:20

标签: javascript html json

我可以通过从后面的代码序列化到下拉列表的值来保留JSON对象吗?

2 个答案:

答案 0 :(得分:0)

DOM元素的标准属性的值可以是满足相关HTML属性要求的任何值。选项元素value attribute必须符合cdata的要求。

答案 1 :(得分:0)

这里的代码我希望它解决你的问题。 这是webservice .asmx扩展类型。

  public class WebService1 : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod( ResponseFormat = ResponseFormat.Json)]
    public List<Employee> SayHellowJson( string name )
    {
        //string result = string.Format( " {1} : {0} ",name,DateTime.Now );
        Employee emp = new Employee{ Name= name , Designation = "Senior Software Engineer" };
        List<Employee> employees = new List<Employee>();
        employees.Add(emp);
        employees.Add(new Employee { Name = "first", Designation = "designation" });
        employees.Add ( new Employee { Name="second", Designation="Designation2" } );
        employees.Add(new Employee {Name="thired" , Designation="Deisgnation4" });

        //JavaScriptSerializer serializer = new JavaScriptSerializer();

        //return serializer.Serialize(emp);
        return employees;
    }
}
[Serializable]
public class Employee
{
    public string Name { get; set; }
    public string Designation { get; set; }
 }
}

有jquery /和html代码... 我将json调用绑定到输入keyup事件意味着当你在texbox中按键时下拉填充。 这是代码     &lt;%@ Page Language =“C#”AutoEventWireup =“true”CodeBehind =“JsonCall.aspx.cs”Inherits =“WebApplication1.JsonCall”%&gt;

<!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 runat="server">
  <script type="text/javascript">
$(function(){
$('#txtname').keyup(function( evt )
{
  $.ajax({
    url: "/WebService1.asmx/SayHellowJson",
    type: "POST",
    dataType:"json",
    data:"{name:'"+Name+"'}",
    contentType : "application/json;  charset=utf-8",
    success: function(msg){
         for (var i = 0 ; i < msg['d'].length ; i ++ ){
              $('#myselect').append('<option value="'+msg['d'][i].Name+'">'+msg['d'][i].Name+'</option>');
         }

        },
    error : function(e){
             alert ( "error " );
        }
  });
});

 });
   </script>

</head>
<body>
<form id="form1" runat="server">
<div>
    <p>
        JSON format call</p>
    Enter Name :
    <input type="text" id="txtname" />
    <input type="button" value="GO" id="btnGO" />
    <br />
    <p id='result'>
    </p>
    </div>
    </form>
    <select id="myselect" name="D1">
      <option></option>
    </select>
 </body>
 </html>