【问题标题】:Update the same modal instead page reload after post in Asp.net MVC在 Asp.net MVC 中发布后更新相同的模式而不是页面重新加载
【发布时间】:2016-01-13 06:35:14
【问题描述】:

我正在使用 Asp.net MVC 4 和 Bootstrap 3 以模式上传新图像,并在上传后以相同模式显示图像。到目前为止,上传工作正常,但我被重定向到视图,而不是更新模式。这是我的代码:

控制器

    [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");
                }
            });
        });

【问题讨论】:

  • 您可能想了解Post/Redirect/Get pattern,以了解为什么您尝试做的事情是个坏主意。
  • 您的表单位于模态框内,并且在该表单内您正在上传图像,并希望在上传后在同一模态框内显示该图像而不关闭或刷新模态框,对吗?
  • @AnilPanwar,是的,你完全正确。
  • 如果要发布数据并保持在同一页面上,则需要使用ajax。由于您有文件输入,因此您将需要使用FormData(例如,请参阅this answer
  • @SinOscuras 我添加了答案。请看

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


【解决方案1】:

这是为了让您了解如何执行它。

像这样将锚点更改为按钮

<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);
        }

});

【讨论】:

  • 谢谢,我检查了您的代码并意识到我没有在Formdata() 中附加任何内容。但是我还有一个问题,你这里提到的show.bs.modal有什么用?
  • 它的引导事件就像 jquery 中的事件(点击,keyup 等)...当模式打开时触发,该按钮使用具有数据目标属性作为模式 ID 的单击按钮。我建议你经历一次引导事件,因为当你使用引导时它会让生活变得更轻松。在 getbootsrap.com 中检查 Javascript 菜单项以获取更多类型的事件
  • @SinOscuras, FormData($('form').get(0)); 自动添加表单输入(包括文件输入)。你不需要附加任何东西
  • 好吧,我只是写了这段代码没有检查它,我写在记事本上并发布以供参考。
  • @AnilPanwar,谢谢,但现在出现了一个新问题。图像未以模式更新。它总是显示缓存的图像。知道为什么会这样吗?
【解决方案2】:

试试这个

[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 );
    }

【讨论】:

  • 谢谢,但这与 Json 无关。
猜你喜欢
  • 2017-03-16
  • 2013-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-22
  • 2021-10-10
  • 2016-10-26
  • 2014-11-21
相关资源
最近更新 更多