動態綁定下拉列表


動態綁定下拉列表

在<select> data-bind的options選項如果綁定到ko.observableArray(),就可以動態新增選項效果,也就是可以利用其完成常見的級聯效果的。

在這一篇文章中,我們用單頁面完成無刷新的前台新增選項和使用MVC完成后台的動態添加2個例子。

范例一:

ViewModel 中聲明一個selectOptions屬性為一個ko.observableArray()對象,並將其設為<select>的 options下拉列表的數據源,再用兩個<input>分別輸入入Text及Value,輸入內容點擊新增按鈕,此時就可看到下拉列表出現 新增的選項內容。

<html xmlns="http://www.w3.org/1999/xhtml">
    
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>
            動態新增下拉列表選項
        </title>
        <script src="Scripts/jquery-2.0.3.js">
        </script>
        <script src="Scripts/knockout-2.3.0.js">
        </script>
        <script type="text/javascript">
            //創建一個View對象
            function ViewModel() {
                var self = this;
                //使用observableArray進行綁定可以動態變更option選項
                self.selectOptions = ko.observableArray([{
                    "text": "請選擇",
                    "value": "0"
                }]);
                self.result = ko.observable("0"); //添加result監控屬性,初始綁定值為0
            }

            $(function() {
                var vm = new ViewModel();
                ko.applyBindings(vm);
                $("#btnAddItem").click(function() {
                    vm.selectOptions.push({
                        "text": $("#txtOptText").val(),
                        "value": $("#txtOptValue").val()
                    });
                });
            });
        </script>
    </head>
    
    <body>
        <div style=" background-color:#0094ff; width:180px; margin:100px auto auto auto;">
            <select style="background-color:ActiveCaption;width:100px" data-bind="options: selectOptions, optionsText: 'text', optionsValue: 'value', value: result">
            </select>
            Value=
            <span data-bind="    text: result">
            </span>
            <div>
                Text:
                <input id="txtOptText" value="選項1" />
            </div>
            <div>
                Value:
                <input id="txtOptValue" value="1" />
            </div>
            <input type="button" value="新增選項" id='btnAddItem' />
        </div>
    </body>

</html>

范例二:Mvc結合knockout.js完成級聯下拉菜單

本例只是為了模擬,所以數據比較簡陋,當然也可以從數據庫中出數據來進行處理。

@ {
    Layout = null;
}

< !DOCTYPE html >

<html > <head > <meta name = "viewport"
content = "width=device-width" / ><title > Index < /title>
    <script src="~/Scripts / jquery - 2.0.3.js "></script>
    <script src="~ / Scripts / knockout - 2.3.0.debug.js "></script>

    </head>
    <body>
      <p>
        <b style="
color: #0094ff ">選擇學生:</b> @Html.DropDownList("
Student ", ViewBag.Students  as SelectList, "請選擇", new { onchange = "
searchLover();
" })
     </p>
      <p data-bind="
visible: selectOptions().length > 0 ">
      <b style="
color: #0094ff ">喜愛的事物:</b>
      <select data-bind="
options: selectOptions,
optionsText: 'Name',
optionsValue: 'Value',
optionsCaption: '請選擇'">
      </select>
</p>
    </body>
    <script type="
text / javascript ">
        function ViewModel() {
            this.selectOptions = ko.observableArray([]);
        }
        var vm = new ViewModel();
        ko.applyBindings(vm);
        function searchLover() {
            var id= $("#Student ").val();
            $.getJSON(
                   "@Url.Action("GetLovers")",
                    { studentId: id},
                    function (data) {
                        vm.selectOptions(data);
            });
        }
</script>
</html>"

-------------------------------------Controller中的數據模擬代碼

using System.Collections.Generic;
using System.Web.Mvc;

namespace KnockFunctionDemo.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            ViewBag.Students = new SelectList(GetStudentList(),"Id","Name");
            return View();
        }
        private static List<Student> GetStudentList()
        {
            return new List<Student>
            {
                new Student{ Id=001, Name="halower"},
                 new Student{ Id=002, Name="rohelm"}
            };
        }
        public JsonResult GetLovers(int studentId)
        {
            var list = new List<Lover>();
            if (studentId == null)
                list= null;
            else if (studentId == 001)
            {
                list.Add(new Lover { Name = "編程", Value = "program" });
                list.Add(new Lover { Name = "女朋友", Value = "GF" });
            }
            else
            {
                list.Add(new Lover { Name = "旅游", Value = "travel" });
                list.Add(new Lover { Name = "家庭", Value = "family" });
            }
            return  Json(list, JsonRequestBehavior.AllowGet);
        }
        
    }

   
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class Lover
    {
        public string Value { get; set; }
        public string Name { get; set; }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM