MVC 前台Form上传文件后台处理后, 页面不跳转

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/stu_20052369/article/details/88774681

1.前台代码

<section class="content">
    <div class="row">
        <div class="box">
            <div class="box-header with-border">
                <p>Please seleet a  file to upload.</p>
                <div class="col-xs-6 col-md-6">
                    @*<form name="fileForm" action="@Url.Action("Import")" method="post" enctype="multipart/form-data">*@
                    <form name="fileForm"  method="post" enctype="multipart/form-data">
                        <div class="input-group">
                            <input type="text" class="form-control" id="path">
                            <span class="input-group-btn">
                                <span type="" class="btn btn-primary" onclick="$('#brower').click()">Browse</span>
                                <input id="brower" name="excelfile" type="file" style="display: none !important;"
                                       onchange="$('#path').val(document.getElementById('brower').value)" />
                            </span>
                        </div>
                        <br />

                    </form>
                    <div class="input-group">
                        <input id="subimtBtn" class="btn btn-success" value="Import" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

2. js代码

$("#subimtBtn").click(function () {
    var form = $("form[name=fileForm]");
    var options = {
        url: "/Dashboard/Import",
        type: 'post',
        success: function (data) {

            data.foo;
            data.baz;

            if (1 == data.foo) {


            }

        }
    };
    form.ajaxSubmit(options);
    //$("#fileForm").submit();  
});

3. 后台处理代码

 [HttpPost]
        public ActionResult Import(HttpPostedFileBase excelfile)
        {
           
            if (excelfile == null || excelfile.ContentLength == 0)
            {
                ViewBag.Error = "Please Select a Budget File<br>";
                //Response.Write("0");
                return View("ValidateRates");
            }
            else
            {

                string targetFolder = Server.MapPath("~/Content/");
                string path = Path.Combine(targetFolder, excelfile.FileName);
                
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                    excelfile.SaveAs(path);
                }
                else
                {
                    excelfile.SaveAs(path);
                }
                
                return Json(new { foo = 1, baz = "Blech" });
            }
        }

猜你喜欢

转载自blog.csdn.net/stu_20052369/article/details/88774681
今日推荐