在asp.net mvc中发布后更新相同的模式而不是页面重新加载

时间:2016-01-13 06:35:15

标签: jquery asp.net-mvc twitter-bootstrap

我使用asp.net mvc 4Bootstrap 3modal上传新图片,并在上传后以同一模式显示图片。到目前为止上传工作正在进行,但是更新模式后,我被重定向到视图。这是我的代码,

控制器

    [HttpPost]
    public ActionResult FlatImageOne(HttpPostedFileBase file, int getFlId)
    {
        if (file != null && file.ContentLength > 0)
        {
            string picName = getFlId.ToString() + "-0";
            WebImage img = new WebImage(file.InputStream);
            string picExt = Path.GetExtension(file.FileName);
            if (picExt == ".jpg" || picExt == ".gif" || picExt == ".jpeg" || picExt == ".png")
            {
                picExt = "PNG";
                string path = System.IO.Path.Combine(Server.MapPath("~/Images/Flats/"), picName);
                var img_cropped = img.Resize(1000, 667, false, true);
                img_cropped.Save(path, picExt);
                TempData["img1_update_success"] = "Image Updated Successfully!";
                return RedirectToAction("FlatImageOne", new { FlId = getFlId });
            }
            else
            {
                TempData["img1_update_fail"] = "Error! Wrong File Type(s)! Please Try Again.";
                return RedirectToAction("FlatImageOne", new { FlId = getFlId });
            }
        }
        else
        {
            TempData["img1_update_fail"] = "Error! Please provide an image file to update.";
            return RedirectToAction("FlatImageOne", new { FlId = getFlId });
        }
    }

查看模态

<div>
    @using (Html.BeginForm("FlatImageOne", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true, "Error! Please provide valid information!")

        <input type="file" name="file" style="width: 100%;" /><br />
        <input type="hidden" name="getFlId" value="@ViewBag.ImgName" />
        <input type="submit" class="btn btn-info" value="Upload" />
    }
</div><br />
<div>
    <img src="~/Images/Flats/@(ViewBag.ImgName)-0.png" alt="your image" class="img-responsive" />
</div>

查看(如果点击链接,此页面会打开模式!)

<script>
    $('.btnInfo').click(function (e) {
        var id = $(this).attr('href');
        e.preventDefault();
        $('#modal-content').load("FlatImageOne?FlId=" + id);
    });
</script>

<a href="@Model.serial" class="btnInfo" data-target="#myModal" data-toggle="modal">Change Featured Image</a>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Change Image</h4>
            </div>
            <div class="modal-body">
                <div id="modal-content"></div>
            </div>
        </div>
    </div>
</div>

如何在上传后重新加载模式而不是重定向到页面?急需这个帮助!感谢。

更新

关于@Stephen Muecke的建议,我在模态的观点中添加了ajax。但我每次尝试上传时都会收到错误警报。这是代码,

        $('#btnUpload').click(function (e) {
            e.preventDefault();
            var formdata = new FormData($('form').get(0));
            $.ajax({
                url: '@Url.Action("FlatImageOne", "Home")',
                type: 'POST',
                data: formdata,
                processData: false,
                contentType: false,
                success: function (data) {
                    alert("Upload successful!");
                },
                error: function () {
                    alert("Error");
                }
            });
        });

2 个答案:

答案 0 :(得分:0)

这可以让您了解如何执行它。

将锚点更改为按钮

<button data-serial="@Model.serial" class="btnInfo" data-target="#myModal" data-toggle="modal">Change Featured Image</<button >

将您的模态修改为:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Change Image</h4>
            </div>
            <div class="modal-body">
               <div> 
                  <input type="file" name="file" id="Upload" />    
                 <input type="hidden"  id="SerailID" />   //Filled on showm.bs.modal event fires on modal opening          
                 <input type="button" id="UploadButton" class="btn btn-info" value="Upload" />
        </div>
        <div id="setImage">
          //Append here image on success
        </div>
            </div>
        </div>
    </div>
</div>

当模态打开时调用show.bs.modal

$('#myModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var serialID= button.data('serial') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.

  $("#SerailID").val(serialID); //Put value to hidden input


  });




$("#UploadButton").on("click",function(){
     e.preventDefault();
    var file = document.getElementById('Upload').files[0];
    var fileName = file.name;
    var SerialID = $("#SerailID").val(); //get serial id from hidden button
    var fd = new FormData();
    fd.append("file", file);
    fd.append("getFlId", SerialID );

    $.ajax({
        url: "Set YOUR URL",
        type:"POST",
        processData: false,
        contentType: false,
        data: fd ,
        success: function (response) {
           //append image after sccess upload.
           $("#setImage").html(" <img src="~/Images/Flats/'+SerialID +'" alt="your image" class="img-responsive" />");
        },
        error: function (er) {
            alert(er);
        }

});

答案 1 :(得分:-1)

试试这个

[HttpPost]
    public ActionResult FlatImageOne(HttpPostedFileBase file, int getFlId)
    {
        var status = false;
        if (file != null && file.ContentLength > 0)
        {
            string picName = getFlId.ToString() + "-0";
            WebImage img = new WebImage(file.InputStream);
            string picExt = Path.GetExtension(file.FileName);
            if (picExt == ".jpg" || picExt == ".gif" || picExt == ".jpeg" || picExt == ".png")
            {
                picExt = "PNG";
                string path = System.IO.Path.Combine(Server.MapPath("~/Images/Flats/"), picName);
                var img_cropped = img.Resize(1000, 667, false, true);
                img_cropped.Save(path, picExt);
                TempData["img1_update_success"] = "Image Updated Successfully!";
                return RedirectToAction("FlatImageOne", new { FlId = getFlId });
            }
            else
            {
                TempData["img1_update_fail"] = "Error! Wrong File Type(s)! Please Try Again.";

             status =true;
            }
        }
        else
        {
            TempData["img1_update_fail"] = "Error! Please provide an image file to update.";
            status =true;
        }

return Json(status );
    }