MVC TIP6:级联菜单

级联菜单最有名的是省市级联,如果你还没有这样的数据库,请从这里下载Province.rar

1:MODEL

准备3个Model,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Province
{
    public int id { get; set; }
    public string provinceID { get; set; }
    public string province { get; set; }
}
public class Province
{
    public int id { get; set; }
    public string provinceID { get; set; }
    public string province { get; set; }
}
public class Area
{
    public int id { get; set; }
    public string areaID { get; set; }
    public string area { get; set; }
    public string father { get; set; }
}

2:Controller部分的数据获取

如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class CityController : Controller
{
    string conn = "Data Source=.;Initial Catalog=ForestFire;User Id=sa;Password=sa;";
 
    public ActionResult Index()
    {
        return View("");
    }
 
    public ActionResult GetProvince()
    {
        if (!Request.IsAjaxRequest())
        {
            return Content("请不要非法方法,这是不道德的行为!");
        }
        string sql = "select * from dbo.povince";
        using (DataSet ds = SqlHelper.ExecuteDataset(conn, CommandType.Text, sql))
        {
            var provinces = DataTableHelper.DataTable2Objects<Province>(ds.Tables[0]);
            return Json(provinces, JsonRequestBehavior.AllowGet);
            //return Json(provinces);
        }
    }
 
    public ActionResult GetCity(string id)
    {
        if (!Request.IsAjaxRequest())
        {
            return Content("请不要非法方法,这是不道德的行为!");
        }
        string sql = "select * from dbo.city where father=@fatherID";
        SqlParameter p1 = new SqlParameter("@fatherID", id);
        using (DataSet ds = SqlHelper.ExecuteDataset(conn, CommandType.Text, sql, p1))
        {
            var citys = DataTableHelper.DataTable2Objects<City>(ds.Tables[0]);
            return Json(citys, JsonRequestBehavior.AllowGet);
            //return Json(provinces);
        }
    }
 
    public ActionResult GetArea(string id)
    {
        if (!Request.IsAjaxRequest())
        {
            return Content("请不要非法方法,这是不道德的行为!");
        }
        string sql = "select * from dbo.area where father=@areaID";
        SqlParameter p1 = new SqlParameter("@areaID", id);
        using (DataSet ds = SqlHelper.ExecuteDataset(conn, CommandType.Text, sql, p1))
        {
            var areas = DataTableHelper.DataTable2Objects<Area>(ds.Tables[0]);
            return Json(areas, JsonRequestBehavior.AllowGet);
            //return Json(provinces);
        }
    }
 
}

3:前台

如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
 
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index.aspx
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript">
        $(document).ready(function () {
            $("#getP").click(function () {
                GetByJquery();
            });
            $("#ddlProvince").change(function () { GetCity() });
            $("#ddlCity").change(function () { GetArea() });
        });
 
        function GetByJquery() {
            $("#ddlProvince").empty();
            //                        $.getJSON("GetProvince", function (result) {
            //                            alert("abc");
            //                            $.each(result, function (i, item) {
            //                                $("<option></option>")
            //                                .val(item["id"])
            //                                .text(item["province"])
            //                                .appendTo($("#ddlProvince"));
            //                            });
            //                            alert("xxx");
            //                            //GetCity();
            //                        });
            htmlobj = $.ajax({
                url: "City/GetProvince",
                async: false,
                complete: function (XmlHttpRequest, textStatus) {
                },
                success: function (result) {
                    $.each(result, function (i, item) {
                        $("<option></option>")
                                            .val(item["provinceID"])
                                            .text(item["province"])
                                            .appendTo($("#ddlProvince"));
                    });
                    GetCity();
                },
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                    var $errorPage = XmlHttpRequest.responseText;
                    alert($("#ErrorMsg", $errorPage).text());
                    //alert($("#ErrorMsg", XmlHttpRequest.responseText).text());
                },
                dataType: "json"
            });
        }
 
        function GetCity() {
            $("#ddlCity").empty();
            alert($("#ddlProvince").val());
            htmlobj = $.ajax({
                url: "City/GetCity/" + $("#ddlProvince").val(),
                async: false,
                complete: function (XmlHttpRequest, textStatus) {
                },
                success: function (result) {
                    $.each(result, function (i, item) {
                        $("<option></option>")
                                            .val(item["cityID"])
                                            .text(item["city"])
                                            .appendTo($("#ddlCity"));
                    });
                    GetArea();
                },
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                    var $errorPage = XmlHttpRequest.responseText;
                    alert($("#ErrorMsg", $errorPage).text());
                    //alert($("#ErrorMsg", XmlHttpRequest.responseText).text());
                },
                dataType: "json"
            });
        }
 
        function GetArea() {
            $("#ddlArea").empty();
            alert($("#ddlCity").val());
            htmlobj = $.ajax({
                url: "City/GetArea/" + $("#ddlCity").val(),
                async: false,
                complete: function (XmlHttpRequest, textStatus) {
                },
                success: function (result) {
                    $.each(result, function (i, item) {
                        $("<option></option>")
                                            .val(item["areaID"])
                                            .text(item["area"])
                                            .appendTo($("#ddlArea"));
                    });
                },
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                    var $errorPage = XmlHttpRequest.responseText;
                    alert($("#ErrorMsg", $errorPage).text());
                    //alert($("#ErrorMsg", XmlHttpRequest.responseText).text());
                },
                dataType: "json"
            });
        }
 
         
 
    </script>
    <input id="getP" name="getP" type="button" value="获取列表" />
    <h2>
        xxx</h2>
    <table>
        <tr>
            <td>
                <select id="ddlProvince"  />
            </td>
            <td>
                <select id="ddlCity" />
            </td>
            <td>
                <select id="ddlArea" />
            </td>
        </tr>
    </table>
</asp:Content>

最后的效果:

image

代码下载:MvcApplication520110801.rar

posted @   陆敏技  阅读(2044)  评论(2编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
Web Counter
Coupon for Contacts
点击右上角即可分享
微信分享提示