博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
创建联动的 DropdownList in ASP.net MVC 3 and jQuery (2)
阅读量:2385 次
发布时间:2019-05-10

本文共 6696 字,大约阅读时间需要 22 分钟。

1. AjaxBindDropdownlistController.cs

using System;

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

namespace MvcAppDemoCly.Controllers

{
    public class AjaxBindDropdownlistController : Controller
    {
        public ActionResult LoadProvince()
        {
            var provinces = Province.GetProvinces();
            return Json(new SelectList(provinces, "Id", "Name"), JsonRequestBehavior.AllowGet);
        }

        public ActionResult LoadCity()

        {
            //string testuservalue = Request.Params["nouservar"];

            int provinceId = -1;

            Int32.TryParse(Request.Params["provinceid"], out provinceId);
            var cities = City.GetCitiesByProvinceId(provinceId);
            //return Json(new SelectList(cities,"Id","Name"), JsonRequestBehavior.AllowGet);
            return Json(cities, JsonRequestBehavior.AllowGet);
        }
        //
        // GET: /AjaxBindDropdownlist/

        public ActionResult Index()

        {
            return View();
        }

        //

        // GET: /AjaxBindDropdownlist/Details/5

        public ActionResult Details(int id)

        {
            return View();
        }

        //

        // GET: /AjaxBindDropdownlist/Create

        public ActionResult CreateProvince()

        {
            return View();
        }

        //

        // POST: /AjaxBindDropdownlist/Create

        [HttpPost]

        public ActionResult CreateProvince(Province p)
        {
            try
            {
                if (!this.ModelState.IsValid)
                {
                    return View();
                }
                if (p != null)
                {
                    // TODO: Add insert logic here
                    Province.InsertProvince(p);
                    return RedirectToAction("Index");
                }
                ViewData["CreateResult"] = "Created Failed!";
                return View();
            }
            catch
            {
                ViewData["CreateResult"] = "Created Failed!";
                return View();
            }
        }

        //

        // GET: /AjaxBindDropdownlist/Create

        public ActionResult CreateCity()

        {
            var provinceList = Province.GetProvinces();
            ViewData["Provinces"] = new SelectList(provinceList, "Id", "Name");
            return View();
        }

        //

        // POST: /AjaxBindDropdownlist/Create

        [HttpPost]

        public ActionResult CreateCity(City c)
        {
            var provinceList = Province.GetProvinces();
            ViewData["Provinces"] = new SelectList(provinceList, "Id", "Name");

            try

            {
                if (!this.ModelState.IsValid)
                {
                    return View();
                }
                if (c != null)
                {
                    // TODO: Add insert logic here
                    City.InsertCity(c);
                    return RedirectToAction("Index");
                }

                ViewData["CreateResult"] = "Created Failed!";

                return View();
            }
            catch
            {
                ViewData["CreateResult"] = "Created Failed!";
                return View();
            }
        }

        //

        // GET: /AjaxBindDropdownlist/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //

        // POST: /AjaxBindDropdownlist/Edit/5

        [HttpPost]

        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //

        // GET: /AjaxBindDropdownlist/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //

        // POST: /AjaxBindDropdownlist/Delete/5

        [HttpPost]

        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

 

2. Index.aspx

 

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

    Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <script src="../../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        function json2string(strObject) {
            var c, i, l, s = '', v, p;
            switch (typeof strObject) {
                case 'object':
                    if (strObject) {
                        if (strObject.length && typeof strObject.length == 'number') {
                            for (i = 0; i < strObject.length; ++i) {
                                v = json2string(strObject[i]);
                                if (s) {
                                    s += ',';
                                }
                                s += v;
                            }
                            return '[' + s + ']';
                        } else if (typeof strObject.toString != 'undefined') {
                            for (i in strObject) {
                                v = strObject[i];
                                if (typeof v != 'undefined' && typeof v != 'function') {
                                    v = json2string(v);
                                    if (s) {
                                        s += ',';
                                    }
                                    s += json2string(i) + ':' + v;
                                }
                            }
                            return '{' + s + '}';
                        }
                    }
                    return 'null';
                case 'number':
                    return isFinite(strObject) ? String(strObject) : 'null'; case 'string': l = strObject.length; s = '"';
                    for (i = 0; i < l; i += 1) {
                        c = strObject.charAt(i);
                        if (c >= ' ') {
                            if (c == '\\' || c == '"') {
                                s += '\\';
                            }
                            s += c;
                        } else {
                            switch (c) {
                                case '\b': s += '\\b'; break;
                                case '\f': s += '\\f'; break;
                                case '\n': s += '\\n'; break;
                                case '\r': s += '\\r'; break;
                                case '\t': s += '\\t'; break;
                                default: c = c.charCodeAt(); s += '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
                            }
                        }
                    }
                    return s + '"';
                case 'boolean': return String(strObject);
                default: return 'null';
            }
        }

        $(document).ready(function () {
            LoadProvince();
            $("#city").append("<option value='-1'>" + "Please select…" + "</option>");
            $("#province").change(function () {//chang事件
                $("#city").empty();
                var provinceid = $("#province").val();
                LoadCity(provinceid);
            });
        });

        function LoadProvince() {//load province
            $.ajax({
                type: "get",
                dataType: "json",
                url: "/AjaxBindDropdownlist/LoadProvince",
                success: function (msg) {
                    var data = msg;
                    $("#province").append("<option value='-1'>" + "Please select…" + "</option>");
                    //alert(json2string(data));
                    //alert(data[0].Text);
                    for (var i = 0; i < data.length; i++) {
                        $("#province").append("<option value='" + data[i].Value + "'>" + data[i].Text + "</option>");
                    }
                }
            });
        }

        function LoadCity(provinceid) {//LoadCity

            $.ajax({

                type: "get",
                dataType: "json",
                url: "/AjaxBindDropdownlist/LoadCity",
                data: { provinceid: provinceid, nouservar: "testvalue" },
                success: function (msg) {
                    var data = msg;
                    //alert(json2string(data));
                    //alert(data[0].Name);
                    for (var i = 0; i < data.length; i++) {
                        $("#city").append("<option value='" + data[i].Id + "'>" + data[i].Name + "</option>");
                    }
                }
            });
        }

    </script>

    <h2>
        Index</h2>
    <%: Html.ActionLink("Create Province","CreateProvince") %>
    <%: Html.ActionLink("Create City","CreateCity") %>
    <br />
    <br />
    <br />
    <div id="SelectTest">
        Province:<select id="province" name="D1">
        </select><br />
        City:
        <select id="city" name="D2">
        </select>
    </div>
</asp:Content>

3. Models

a) ProvinceModel.cs

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MvcAppDemoCly.Models

{
    public class Province
    {
        public int Id { get; set; }
        [Required]
        [DisplayName("Province Name")]
        public string Name { get; set; }

        [DisplayName("Description")]

        public string Description { get; set; }
    }
}

b) CityModel.cs

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MvcAppDemoCly.Models

{
    public class City
    {
        public int Id { get; set; }
        [Required]
        [DisplayName("Province Name")]
        public string Name { get; set; }

        [DisplayName("Description")]

        public string Description { get; set; }

        public int ProvinceId { get; set; }

    }
}

 

转载地址:http://fqjab.baihongyu.com/

你可能感兴趣的文章
SQL命令查询Oracle存储过程信息(代码内容等)
查看>>
Oracle创建删除用户、角色、表空间、导入导出、...命令总结
查看>>
oracle查看系统存储过程
查看>>
VBS下载者
查看>>
安全度量标准
查看>>
Zimbra 0day exploit / Privilegie escalation via LFI
查看>>
Zend-Framework - Full Info Disclosure
查看>>
Passive DNS
查看>>
近期要购买的图书
查看>>
Tools: NOSQLMap - SQLMap for nosql database
查看>>
waf度量标准
查看>>
Bypassing Microsoft Windows ASLR with a little help by MS-Help
查看>>
ASLR/DEP绕过技术概览
查看>>
域渗透命令
查看>>
bitsadmin 下载文件命令示例
查看>>
基于语法分析的PHP webshell扫描工具–Pecker Scanner
查看>>
基于SAML的单点登录介绍
查看>>
eBay信用评价体系全解析
查看>>
Amazon 的 Dynamo 架构
查看>>
比Hive高效7倍Facebook推新一代查询引擎Presto
查看>>