Ajax 省市联动更新,文末更新批量上传帮助类

原创 2015年11月18日 16:59:06

效果如下,省市2级联动,企业1级

js代码

<script type="text/javascript">

        $(document).ready(function () {
            //获取市列表
            $("#Province").change(function () {
                getCity($(this).val());
                document.getElementById('province').setAttribute("value", $(this).val());
            });
            //获取镇列表
            $("#City").change(function () { getTown($(this).val()); });
            //获取企业类型列表
            $("#EntCategoryID").change(function () { getEntRank($(this).val()); });
        })

        function getCity(value) {
            //$("#City").html(""); //清空
            $.ajax({
                type: "post",
                url: "GetCityList",               
                data: { provinveCode: value },
                dataType: "json",
                success: function (data) {
                    if (data.count > 0) {
                        $("#City option").remove();
                        $.each(data.Pos, function (i, item) {
                            $("#City").append("<option value='" + item.CityID + "'>" + item.CityName + "</option>");
                        });
                        getTown(item[0].CityID);
                    }
                    else {
                        $("#City option").remove();
                        $("#City").append("<option value=''>--请选择--</option>")

                    }
                },
                error: function (data) {
                    alert(data);
                }
            });
        }
        function getTown(value1) {
            $.ajax({
                type: "post",
                url: "GetTownList",
                data: { cityCode: value1 },
                dataType: "json",
                success: function (data) {
                    if (data.count > 0) {
                        $("#Town option").remove();
                        $.each(data.Pos, function (i, item) {
                            $("#Town").append("<option value='" + item.CountyID + "'>" + item.CountyName + "</option>");
                        });
                    }
                    else {
                        $("#Town option").remove();
                        $("#Town").append("<option value=''>--请选择--</option>")

                    }
                },
                error: function (data) {
                    alert(data);
                }
            });
        }
        function getEntRank(value)
        {
            $.ajax({
                type: "post",
                url: "/Enterprise/Home/GetEntRankList",
                data: { EntCategoryID: value },
                dataType: "json",
                success: function (data) {
                    if (data.count > 0) {
                        $("#EntRank option").remove();
                        $.each(data.Pos, function (i, item) {
                            $("#EntRank").append("<option value='" + item.EntRankID + "'>" + item.EntRankName + "</option>");
                        });
                    }
                    else {
                        $("#EntRank option").remove();
                        $("#EntRank").append("<option value=''>--请选择--</option>")

                    }
                },
                error: function (data) {
                    alert(data);
                }
            });
        }
    </script>

控制器代码

    #region   省市联动
        [HttpPost]
        public JsonResult GetCityList()
        {
            string ProvinceID = Request["provinveCode"].ToString();
            //string ProvinceID = "350000";
            var City = (from t in ct.C_City where t.ProvinceID == ProvinceID select t).ToList();
            return Json(new { count = City.Count, Pos = City });
        }


        public JsonResult GetTownList()
        {
            string CityID = Request["cityCode"].ToString();
            var Town = (from t in ct.C_County where t.CityID == CityID select t).ToList();
            return Json(new { count = Town.Count, Pos = Town });
        }

        #endregion

        #region   企业类型联动
        [HttpPost]
        public JsonResult GetEntRankList()
        {
            string EntCategoryID = Request["EntCategoryID"].ToString();
            //string ProvinceID = "350000";
            var Rank = (from t in ct.C_EntRank where t.EntCategoryID == EntCategoryID select t).ToList();
            return Json(new { count = Rank.Count, Pos = Rank });
        }


    

        #endregion

视图代码


                <li><label>所在省:</label>
                @Html.DropDownList("ProvinceID", ServicePlatform.Lib.PageHelper.GetCodeTable(new ServicePlatform.Models.CodeTableContext(), "C_Province", "ServicePlatform.Models"), new { id = "Province", name = "Province", @class = "dfinput" })</li>
                <li><label>所在市:</label>
                @Html.DropDownList("CityID", new List<SelectListItem>(), new { id = "City", name = "City", @class = "dfinput" })</li>
                <li><label>所在(区/县):</label>
                @Html.DropDownList("CountyID", new List<SelectListItem>() as IEnumerable<SelectListItem>, new { id = "Town", name = "Town", @class = "dfinput" })</li>
                @*隐藏字段用于在js调用,设置url路径*@
                @Html.Hidden("GetCityList", Url.Action("GetCityList", "Home"))
                @Html.Hidden("GetTownList", Url.Action("GetTownList", "Home"))


               
                
                <li>
                    <label>企业类型代码</label>
                    @Html.DropDownList("EntCategoryID", ServicePlatform.Lib.PageHelper.GetCodeTable(new ServicePlatform.Models.CodeTableContext(), "C_EntCategory", "ServicePlatform.Models"), new { @class = "dfinput" })
                    <i>*请输入 企业类型代码</i>
                </li>
                <li>
                    
                    <label>企业级别</label>
                    @Html.DropDownList("EntRank", ServicePlatform.Lib.PageHelper.GetCodeTable(new ServicePlatform.Models.CodeTableContext(), "C_EntRank", "ServicePlatform.Models",2), new { @class = "dfinput" })

                    <i>*请选择 企业级别</i>
                </li>

代码表帮助类代码

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServicePlatform.Areas.Permission.Lib;
using System.Reflection;
namespace ServicePlatform.Lib
{
    public class PageHelper
    {

        public static List<SelectListItem> GetCodeTable(DbContext db, string tableName, string nameSpace, int textIndex = 1,int valueIndex = 0)
        {
          
            string fullName = nameSpace + "." + tableName;
            var obj = Assembly.GetExecutingAssembly().CreateInstance(fullName);

             List<SelectListItem>items=new List<SelectListItem>();
           
            var datas = db.Database.SqlQuery(obj.GetType(), "select * from "+tableName ,new object[]{});
            
             foreach (var data in datas)
             {
                var item= PermissionHelper.GetInfo(data)[1];
                items.Add(new SelectListItem() {  Value = item[valueIndex],Text = item[textIndex] });
             }

             return items;
        }

    }
}



以下是同一页面多文件提交的帮助类和调用实例

运行效果


控制器代码

using ServicePlatform.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServicePlatform.Lib;
using ServicePlatform.Config;
namespace ServicePlatform.Areas.Enterprise.Controllers
{
    public class HomeController : Controller
    {


        //
        // GET: /Enterprise/Home/
        EnterpriseContext db = new EnterpriseContext();
        CodeTableContext ct = new CodeTableContext();

        #region   省市联动
        [HttpPost]
        public JsonResult GetCityList()
        {
            string ProvinceID = Request["provinveCode"].ToString();
            //string ProvinceID = "350000";
            var City = (from t in ct.C_City where t.ProvinceID == ProvinceID select t).ToList();
            return Json(new { count = City.Count, Pos = City });
        }


        public JsonResult GetTownList()
        {
            string CityID = Request["cityCode"].ToString();
            var Town = (from t in ct.C_County where t.CityID == CityID select t).ToList();
            return Json(new { count = Town.Count, Pos = Town });
        }

        #endregion

        #region   企业类型联动
        [HttpPost]
        public JsonResult GetEntRankList()
        {
            string EntCategoryID = Request["EntCategoryID"].ToString();
            //string ProvinceID = "350000";
            var Rank = (from t in ct.C_EntRank where t.EntCategoryID == EntCategoryID select t).ToList();
            return Json(new { count = Rank.Count, Pos = Rank });
        }


    

        #endregion
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult T_Enterprise_Add()
        {

          
            return View();
        }
        [HttpPost]
        public ActionResult T_Enterprise_Add(T_Enterprise f, 
            HttpPostedFileBase EntLogo,
            HttpPostedFileBase[] EntAdPics,
            HttpPostedFileBase[] EntPhotos,
            HttpPostedFileBase[] EntVideos,
            HttpPostedFileBase[] EntPPTs,
            HttpPostedFileBase[] EntFiles)
        {

            f.EntLogo = FileOperate.UploadFile(EntLogo, "/UserFiles/Enterprise/Home/EntLogo/");
            f.EntAdPics = FileOperate.UploadFile(EntAdPics, "/UserFiles/Enterprise/Home/EntAdPics/");
            f.EntPhotos = FileOperate.UploadFile(EntPhotos, "/UserFiles/Enterprise/Home/EntPhotos/");
            f.EntVideos = FileOperate.UploadFile(EntVideos, "/UserFiles/Enterprise/Home/EntVideos/");
            f.EntPPTs = FileOperate.UploadFile(EntPPTs, "/UserFiles/Enterprise/Home/EntPPTs/");
            f.EntFiles = FileOperate.UploadFile(EntFiles, "/UserFiles/Enterprise/Home/EntFiles/");

            f.UserID = (Session["Vars"] as Vars).UserID;
            f.RegisterTime = DateTimeFormat.GetTime();
            f.UpdateTime = DateTimeFormat.GetTime();
            f.EntState = 1;//默认不锁
            f.InfoLocked = 1;//默认不锁
            db.T_Enterprise.Add(f);
            db.SaveChanges();
            return View();
        }

      
    }
}


视图代码

@{
    ViewBag.Title = "T_Enterprise_Add";
}


<!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>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>添加记录</title>
    <link href="~/Areas/Enterprise/Content/Admin/css/style.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            //获取市列表
            $("#Province").change(function () {
                getCity($(this).val());
                document.getElementById('province').setAttribute("value", $(this).val());
            });
            //获取镇列表
            $("#City").change(function () { getTown($(this).val()); });
            //获取企业类型列表
            $("#EntCategoryID").change(function () { getEntRank($(this).val()); });
        })

        function getCity(value) {
            //$("#City").html(""); //清空
            $.ajax({
                type: "post",
                url: "GetCityList",               
                data: { provinveCode: value },
                dataType: "json",
                success: function (data) {
                    if (data.count > 0) {
                        $("#City option").remove();
                        $.each(data.Pos, function (i, item) {
                            $("#City").append("<option value='" + item.CityID + "'>" + item.CityName + "</option>");
                        });
                        getTown(item[0].CityID);
                    }
                    else {
                        $("#City option").remove();
                        $("#City").append("<option value=''>--请选择--</option>")

                    }
                },
                error: function (data) {
                    alert(data);
                }
            });
        }
        function getTown(value1) {
            $.ajax({
                type: "post",
                url: "GetTownList",
                data: { cityCode: value1 },
                dataType: "json",
                success: function (data) {
                    if (data.count > 0) {
                        $("#Town option").remove();
                        $.each(data.Pos, function (i, item) {
                            $("#Town").append("<option value='" + item.CountyID + "'>" + item.CountyName + "</option>");
                        });
                    }
                    else {
                        $("#Town option").remove();
                        $("#Town").append("<option value=''>--请选择--</option>")

                    }
                },
                error: function (data) {
                    alert(data);
                }
            });
        }
        function getEntRank(value)
        {
            $.ajax({
                type: "post",
                url: "/Enterprise/Home/GetEntRankList",
                data: { EntCategoryID: value },
                dataType: "json",
                success: function (data) {
                    if (data.count > 0) {
                        $("#EntRank option").remove();
                        $.each(data.Pos, function (i, item) {
                            $("#EntRank").append("<option value='" + item.EntRankID + "'>" + item.EntRankName + "</option>");
                        });
                    }
                    else {
                        $("#EntRank option").remove();
                        $("#EntRank").append("<option value=''>--请选择--</option>")

                    }
                },
                error: function (data) {
                    alert(data);
                }
            });
        }
    </script>

</head>

<body>

    <div class="place">
        <span>位置:</span>
        <ul class="placeul">
            <li><a href="#">首页</a></li>
            <li><a href="#">添加记录</a></li>
        </ul>
    </div>


    <form action="/Enterprise/Home/T_Enterprise_Add" method="post" enctype="multipart/form-data">

      

        <div class="formbody">

            <div class="formtitle"><span>添加记录</span></div>

            <ul class="forminfo">
                <li>
                    <label>企业编号</label>
                    <input name="Ent_No" type="text" class="dfinput" />
                    <i>*请输入 企业编号</i>
                </li>
                <li>
                    <label>企业名称</label>
                    <input name="Ent_Name" type="text" class="dfinput" />
                    <i>*请输入 企业名称</i>
                </li>

                <li><label>所在省:</label>
                @Html.DropDownList("ProvinceID", ServicePlatform.Lib.PageHelper.GetCodeTable(new ServicePlatform.Models.CodeTableContext(), "C_Province", "ServicePlatform.Models"), new { id = "Province", name = "Province", @class = "dfinput" })</li>
                <li><label>所在市:</label>
                @Html.DropDownList("CityID", new List<SelectListItem>(), new { id = "City", name = "City", @class = "dfinput" })</li>
                <li><label>所在(区/县):</label>
                @Html.DropDownList("CountyID", new List<SelectListItem>() as IEnumerable<SelectListItem>, new { id = "Town", name = "Town", @class = "dfinput" })</li>
                @*隐藏字段用于在js调用,设置url路径*@
                @Html.Hidden("GetCityList", Url.Action("GetCityList", "Home"))
                @Html.Hidden("GetTownList", Url.Action("GetTownList", "Home"))


               
                
                <li>
                    <label>企业类型代码</label>
                    @Html.DropDownList("EntCategoryID", ServicePlatform.Lib.PageHelper.GetCodeTable(new ServicePlatform.Models.CodeTableContext(), "C_EntCategory", "ServicePlatform.Models"), new { @class = "dfinput" })
                    <i>*请输入 企业类型代码</i>
                </li>
                <li>
                    
                    <label>企业级别</label>
                    @Html.DropDownList("EntRank", ServicePlatform.Lib.PageHelper.GetCodeTable(new ServicePlatform.Models.CodeTableContext(), "C_EntRank", "ServicePlatform.Models",2), new { @class = "dfinput" })

                    <i>*请选择 企业级别</i>
                </li>



                <li>
                    <label>企业地址</label>
                    <input name="EntAddress" type="text" class="dfinput" />
                    <i>*请输入 企业地址</i>
                </li>
                <li>
                    <label>企业简介</label>
                    <input name="EntResume" type="text" class="dfinput" />
                    <i>*请输入 企业简介</i>
                </li>
                <li>
                    <label>企业Logo</label>
                    <input name="EntLogo" type="file"  class="dfinput" />
                    <i>*请上传 企业Logo</i>
                </li>


                <li>
                    <label>轮播广告图</label>
                    <input name="EntAdPics" type="file" multiple="multiple" class="dfinput" />
                    <i>*请上传 轮播广告图</i>
                </li>
                <li>
                    <label>企业介绍图集</label>
                    <input name="EntPhotos" type="file" multiple="multiple" class="dfinput" />
                    <i>*请上传 企业介绍图集</i>
                </li>
                <li>
                    <label>企业视频集</label>
                    <input name="EntVideos" type="file" multiple="multiple" class="dfinput" />
                    <i>*请上传 企业视频集</i>
                </li>
                <li>
                    <label>企业PPT集</label>
                    <input name="EntPPTs" type="file" multiple="multiple" class="dfinput" />
                    <i>*请上传 企业PPT集</i>
                </li>
                <li>
                    <label>企业资源文件</label>
                    <input name="EntFiles" type="file" multiple="multiple" class="dfinput" />
                    <i>*请上传 企业资源文件</i>
                </li>
               
               
             
                <li>
                    <label>邮箱</label>
                    <input name="Email" type="text" class="dfinput" />
                    <i>*请输入 邮箱</i>
                </li>
                <li>
                    <label>联系方式</label>
                    <input name="Contectinfo" type="text" class="dfinput" />
                    <i>*请输入 联系方式</i>
                </li>




                @* <li>
        <label>注册时间</label>
        <input name="RegisterTime" type="text" class="dfinput" />
        <i>*请输入 注册时间</i>
    </li>


        <li>
        <label>登录名</label>
        <input name="UserID" type="text" class="dfinput" />
        <i>*请输入 登录名</i>
    </li>
    <li>
        <label>企业状态</label>
        <input name="EntState" type="text" class="dfinput" />
        <i>*请输入 企业状态</i>
    </li>
    <li>
        <label>更新时间</label>
        <input name="UpdateTime" type="text" class="dfinput" />
        <i>*请输入 更新时间</i>
    </li>
    <li>
        <label>是否锁定</label>
        @Html.DropDownList("InfoLocked", ServicePlatform.Lib.PageHelper.GetCodeTable(new ServicePlatform.Models.CodeTableContext(), "C_EditStatus", "ServicePlatform.Models"), new { @class = "dfinput" });

        <i>*请选择 是否锁定</i>
    </li>*@
                <li><label> </label><input name="" type="submit" class="btn" value="保存" /></li>

            </ul>


        </div>
    </form>

</body>

</html>






文件上传帮助类更新 2015/11/18

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ServicePlatform.Lib
{
    public static  class FileOperate
    {
        public static bool DeleteFlie(string FilePath)
        {
            string AbsoluteFilePath = System.Web.HttpContext.Current.Server.MapPath(FilePath);//转换物理路径 
            if (System.IO.File.Exists(AbsoluteFilePath))//判断文件是否存在
            {
                System.IO.File.Delete(AbsoluteFilePath);//执行IO文件删除,需引入命名空间System.IO; 
                return true;
            }
            else
            {
                return false ;
            }
           
        }
        public static void DeleteFlie(List<string> FilePaths)
        {
            foreach (var FilePath in FilePaths)
            {
                DeleteFlie(FilePath);
            }

        }

        public static string UploadFile(HttpPostedFileBase file, string SaveDirectory = "/Content/files/Shop/")
        {
            if (file != null)
            {
                //构造文件上传路径(文件名为用户ID)
                string strFileTypeLimit = "image";

                int IsPicType = file.ContentType.IndexOf(strFileTypeLimit);
                //if (Photo.FileName.ToString() != "" && IsPicType != -1 && Photo.ContentLength < 20971520)
                string Ora_FileName = System.IO.Path.GetFileName(file.FileName);
                string Cur_FileName = DateTime.Now.ToBinary().ToString() + "." + Ora_FileName.Substring(Ora_FileName.LastIndexOf(".") + 1);
                string filePath = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath(SaveDirectory), Cur_FileName);
                //保存文件
                file.SaveAs(filePath);
                string End_filePath = SaveDirectory + Cur_FileName;
                return End_filePath;
            }
            else
            {
                return "";
            }
        }
        public static string UploadFile(HttpPostedFileBase[] files, string SaveDirectory = "/Content/files/Shop/")
        {
            string filePath = "";
             if (files != null)
                {
                    foreach (var file in files)
                    {
                       filePath+= UploadFile(file, SaveDirectory)+";";
                    }
                    if (filePath.Length>0&&filePath[filePath.Length - 1] == ';')
                    {
                        filePath = filePath.Substring(0, filePath.Length - 1);
                    }
                }     
               
                return filePath;    
        }
       
        public static string UpdateOldFile(string OldFilePath,HttpPostedFileBase NewFile, string SaveDirectory = "/Content/files/Shop/")
        {
                //删除旧文件
                DeleteFlie(OldFilePath);
                //添加新文件
                return UploadFile(NewFile, SaveDirectory);
        }
        public static string UpdateOldFile(string OldFilePaths, HttpPostedFileBase[] NewFiles, string SaveDirectory = "/Content/files/Shop/")
        {
            //删除旧文件
            DeleteFlie(EncryptString.UnPackString( OldFilePaths));
            //添加新文件
            return UploadFile(NewFiles, SaveDirectory);
        }
        public static string UpdateOldFile(List<string> OldFilePaths, HttpPostedFileBase[] NewFiles, string SaveDirectory = "/Content/files/Shop/")
        {
            //删除旧文件
            DeleteFlie(OldFilePaths);
            //添加新文件
            return UploadFile(NewFiles, SaveDirectory);
        }
    }
}




版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

jquery插件 ajaxfileuploa异步上传文件和 ajax 批量请求的处理方法

因工作需求,碰到这些问题,下面把这些问题及解决方法分享大家  众所周知jquery 的ajax 是相当的简单及实用且兼容各类浏览器,但殊不知其原生不支持 ajax 文件上传,于网上百度查找插...

JQUERY AJAX+STRUTS2批量上传文件

ACTION代码   package ul; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; ...

xheditor HTML编辑器,新闻编辑器初始方法,ajax图片批量上传,添加一个8、13、14px字体

下载一个xheditor-1.1.14 放在web项目Scripts/目录下 将文件夹下xheditor-1.1.14/demos/ 的 saveremoteimg.aspx打开 , 修改 at...

SpringMVC+Ajax文件批量上传和下载

今天做了文件的上传下载,小小总结一下,基本的web项目建立及SpringMVC框架搭建此处不详细写出来了。 上传form:               上传Ajax: ...

ajax批量上传s打

ajax批量上传,使用JQuery插件ajaxFileUpload,后台SpringMVC对多文件进行处理

asp.net mvc 、 ajax 批量上传文件

asp.net mvc 、 ajax 批量上传文件

JS学习32:html5拖拽图片批量ajax无刷新进度上传

1、前端拖拽图片 之前有篇文章说到HTML5的拖拽(drag、drop,详见:/post/jquery-plugin-1-jquery-drag-and-html5-draggable-api-...

【.Net码农】C#.net文件批量上传解决方案附下载(swfupload)2015-8-28更新

http://www.86y.org/art_detail.aspx?id=232 C#.net文件批量上传解决方案附下载(swfupload)2015-8-28更新 用声音读...

ajax异步批量上传文件demo

  • 2016年07月12日 21:31
  • 403KB
  • 下载

基于jquery ajax 无刷新 文件批量上传插件 GooUploader整合struts2实现上传

今天下午安排了一个任务:要实现多文件上传,也就是批量上传文件。相信单个文件上传很多人都实现过,批量上传也有不少人实现过,我之前批量上传的做法是利用js或jquery来动态添加删除的。感觉在用户体验上也...
  • ocean_30
  • ocean_30
  • 2011年09月04日 19:19
  • 13635
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Ajax 省市联动更新,文末更新批量上传帮助类
举报原因:
原因补充:

(最多只允许输入30个字)