在MVC4 @Razor模板中使用ajax上传控件 uploadfile

来源:互联网 发布:mvvm 知乎 编辑:程序博客网 时间:2024/06/05 03:55

_LayoutForCustomer.cshtml :

<!DOCTYPE html><html lang="zh">    <head>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>        <meta charset="utf-8" />        <title>@ViewBag.Title - 这是客户管理的布局页</title>        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />        <meta name="viewport" content="width=device-width" />        @Styles.Render("~/Content/css")        @Scripts.Render("~/bundles/jquery")        @Scripts.Render("~/bundles/modernizr")        @*<script src="@Url.Content("~/Scripts/jquery.uploadfile.min.js")" type="text/javascript"></script>*@        <link href="@Url.Content("~/Content/uploadfile.min.css")" rel="stylesheet" type="text/css" />        @*<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>*@        <script src="@Url.Content("~/Scripts/jquery.uploadfile.min.js")" type="text/javascript"></script>    </head>    <body>        <header>            <div class="content-wrapper">                <div class="float-left">                    <p class="site-title">@Html.ActionLink("导航栏也是应该在左侧", "Index", "Home")</p>                </div>                <div class="float-right">                    <section id="login">                        @Html.Partial("_LoginPartial")                    </section>                    <nav>                        <ul id="menu">                            <li>@Html.ActionLink("小牛自白", "Index", "Home")</li>                            <li>@Html.ActionLink("小牛课堂", "Classroom", "Home")</li>                            <li>@Html.ActionLink("小牛问答", "QA", "Home")</li>                            <li>@Html.ActionLink("小牛资讯", "Information", "Home")</li>                        </ul>                    </nav>                </div>            </div>        </header>        <div id="body">            @*@RenderSection("featured", required: false)            <section class="content-wrapper main-content clear-fix">*@                @RenderBody()            @*</section>*@        </div>        <footer>            <div class="content-wrapper">                <div class="float-left">                    <p>&copy; @DateTime.Now.Year - 我的 ASP.NET MVC 应用程序</p>                </div>            </div>        </footer>        @*@Scripts.Render("~/bundles/jquery")        @RenderSection("scripts", required: false)*@    </body></html>

页面老是不出样式的原因在于最后的

@*@Scripts.Render("~/bundles/jquery")        @RenderSection("scripts", required: false)*@

这两行。
补充:这两天发现经常出现这个问题,最后总结了一下,就是因为在这两个引用文件

<link href="@Url.Content("~/Content/uploadfile.min.css")" rel="stylesheet" type="text/css" /><script src="@Url.Content("~/Scripts/jquery.uploadfile.min.js")" type="text/javascript"></script>

的后面 重复引用jquery库的原因。因为这个是依赖于jquery的。

效果图:
这里写图片描述

index.html

@{    Layout = "~/Views/Shared/_LayoutForCustomer.cshtml";    //Layout = "~/Views/Shared/_LayoutCustomer0.cshtml";}<body>    <form id="abc" method="post" action="UpLoad" enctype="multipart/form-data" encoding="multipart/form-data" style="height:100%">        <div id="advancedUpload">        </div>    </form>    <script type="text/javascript">        var uploadObj = $("#abc div[id=advancedUpload]").uploadFile({            url: "/Tools/UpLoad",            multiple: false,            autoSubmit: true,            fileName: "myfile",            //formData: { "selectname": $("#select1").val() },            maxFileSize: 1024 * 10000,            maxFileCount: 100,            showStatusAfterSuccess: false,            abortStr: "停止",            cancelStr: "停止",            doneStr: "上传",            multiDragErrorStr: "删除文件是不允许的.",            extErrorStr: "错误:",            sizeErrorStr: "错误:",            uploadErrorStr: "上传失败!",            dynamicFormData: function () {                //var data ="XYZ=1&ABCD=2"; var data ={"XYZ":1,"ABCD":2};                //return { "selectname": $("#from select[id=select1]").val() };                return { "selectname": "港口信息" };            },            returnType: 'json',            onSuccess: function (files, data, xhr, pd) {                //console.info(files, data, xhr, pd);                if (data.ref)                    alert("上传成功!");                else                    alert("上传失败!");                //files: list of files //data: response from server //xhr : jquer xhr object            },            allowedTypes: "xlsx"        });    </script></body>

form 标签必须有,id 必须有 并且在下面的脚本中使用,子页面可以不引用uploadfile的 样式文件和脚本文件,但是在布局页面必须引用。

ToolsController.cs

[HttpPost]        public JsonResult UpLoad(string selectname)        {            try            {                NameValueCollection nvc = System.Web.HttpContext.Current.Request.Form;                HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;                Stream imgPath = null;                //string SavePath = null;       长传地址                if (hfc.Count > 0)                {                    imgPath = hfc[0].InputStream;                    //SavePath = "/testUpload" + hfc[0].FileName;                    //string PhysicalPath = Server.MapPath(SavePath); 服务器相对地址                    //hfc[0].SaveAs(SavePath);                        保存到服务器                }                string strPath = string.Empty;                if (imgPath != null)                {                    //var postedFileLength = postedFile.ContentLength;                    //var postedFileStream = postedFile.InputStream;                    //var postedFileData = new byte[postedFileLength];                    //postedFileStream.Read(imgPath);                    var workbook = new XLWorkbook(imgPath);                    var wsYingYe = workbook.Worksheet(1);                    var firstPossibleAddressYingYe = wsYingYe.Row(1).FirstCell().Address;                    var lastPossibleAddressYingYe = wsYingYe.LastCellUsed().Address;                    // Get a range with the remainder of the worksheet data (the range used)                    var companyRangeYingYe = wsYingYe.Range(firstPossibleAddressYingYe, lastPossibleAddressYingYe).RangeUsed();                    // Treat the range as a table (to be able to use the column names)                    var companyTableYingYe = companyRangeYingYe.AsTable();                    // Get the list of company names                    var RowYingYe = companyTableYingYe.DataRange.Rows();                    int sum = 0;                    foreach (var item in RowYingYe)                    {                        Ge_PortModels port = new Ge_PortModels();                        port.Port_PY = item.Field("拼音").GetString();                        port.Port_Name = item.Field("港口").GetString();                        port.Port_Area = item.Field("地区").GetString();                        port.Port_Code = item.Field("代码").GetString();                        port.Sort+=1;                        port.CreateDate = DateTime.Now;                        port.CreateUserID = 1;//此处应该获取当前用户id                        port.IsVisible = true;                        _iport.Create(port);                    }                    if (sum == RowYingYe.Count())                    {                        return Json(new { ret = true, Message = "验证成功" });                    }                    else                    {                        return Json(new { ret = false, Message = "验证失败" });                    }                }                return Json(new { ret = false, Message = "上传失败" });            }            catch (Exception e)            {                return Json(new { ret = false, Message = "代码出现错误,崩溃"+e.ToString() });            }        }
0 0
原创粉丝点击