通过Bootstrap Modal对话框的ASP.Net MVC文件上传重定向浏览器

时间:2018-07-18 13:38:58

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

我有一个基本形式,很少有文本字段,并且在引导模式对话框(引导程序4)上有一个文件上传控制器。下面是我的代码:

型号:

public class DemoContent
{
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }

    [RegularExpression("([0-9]+)",ErrorMessage = "Age must be numbers only")]
    public int Age { get; set; }

    [EmailAddress]
    public string Email { get; set; }

    [DataType(DataType.Upload)]
    [Display(Name = "Image")]
    public HttpPostedFileBase ImageUrl { get; set; }

}

JavaScript

  $(function() {
        $("a[data-modal=demoPopup]").on("click", function () {
            $("#demoModalContent").load(this.href, function () {
                $("#demoModal").modal({ keyboard: true }, "show");

                $("#demoForm").submit(function () {

                    if ($("#demoForm").valid()) {

                        var files = $("ImageUrl").get(0).files;
                        var data = $(this).serialize();
                        data.append("ImageUrl", files[0]);

                        $.ajax({
                            url: this.action,
                            type: this.method,
                            data: $(this).serialize(),
                            success: function (result) {
                                if (result.success) {
                                    $("#demoModal").modal("hide");
                                    location.reload();
                                } else {
                                    $("#MessageToClient").text(result.message);
                                }
                            },
                            error: function () {
                                $("#MessageToClient").text("The web server had an error.");
                            }
                        });
                        return false;
                    }
                });
            });
            return false;
        });

控制器:

  [HttpPost]
    public ActionResult Create(DemoContent model)
    {
        if (model.Age > 55)
        {
            var file = model.ImageUrl;
            return Json(new { success = true });
        }
        else
        {
            return Json(new { success = false,message="Invalid Data" });
        }
    }

现在,当我打开弹出窗口时,当我提交表单时,它也将与文件一起进入控制器。但是问题是一旦服务器返回成功消息,弹出窗口就会在空白页中显示该消息,而不是捕获该消息并刷新当前页面或显示该消息。知道为什么会这样。

链接到源文件:https://drive.google.com/open?id=1W3H3kFEpHJWfaf7_UnJI3O5I900GxyC7

3 个答案:

答案 0 :(得分:0)

可能是您在document.ready()函数中编写了javascripts函数,这就是为什么它再次刷新的原因。

答案 1 :(得分:0)

编写如下JavaScript代码:

$(function() {
        $("a[data-modal=demoPopup]").on("click", function () {
            $("#demoModalContent").load(this.href, function () {
                $("#demoModal").modal({ keyboard: true }, "show");

                $("#demoForm").submit(function (event) { // Pass the event as parameter to the function.

                    event.preventDefault(); // I have added these two lines
                    event.stopImmediatePropagation();

                    if ($("#demoForm").valid()) {

                        var files = $("ImageUrl").get(0).files;
                        var data = $(this).serialize();
                        data.append("ImageUrl", files[0]);

                        $.ajax({
                            url: this.action,
                            type: this.method,
                            data: $(this).serialize(),
                            success: function (result) {
                                if (result.success) {
                                    $("#demoModal").modal("hide");
                                    location.reload();
                                } else {
                                    $("#MessageToClient").text(result.message);
                                }
                            },
                            error: function () {
                                $("#MessageToClient").text("The web server had an error.");
                            }
                        });
                        return false;
                    }
                });
            });
            return false;
        });

答案 2 :(得分:-1)

我想您应该安装并使用Microsoft.Unobtrusive.Validation和* .Ajax,如果您希望更新模态(我这样问您...)。这样,您可以使用类似于以下示例的代码,该代码可以更新您的模态(几天前在项目中使用过):

模式:

        @using (Ajax.BeginForm("Login", new { Controller = "Home", area = "" }, new AjaxOptions() { OnSuccess = "onSuccessLogin", HttpMethod = "POST", UpdateTargetId = "loginmodalbody"}, new { id = "loginForm" }))
        {
            <div class="modal-body" id="loginmodalbody">
                <div class="text-danger loginfailed"></div>
                <div class="container">
                    <div class="card border-primary mb-3" style="margin: 0 auto;">
                        <div class="card-body">
                            @Html.Partial("~/Views/Shared/Modals/LoginModalBody.cshtml")                           
                        </div>
                    </div>
                    <div class="container">
                        <span><a onclick="alert('Leads to pw info')" href="#">Forgot password?</a></span>
                    </div>
                    <br />
                    <button class="btn btn-primary btn-block buttonlogin">Login</button>
                </div>                                      
                <br />
            </div>
        }

模体:

@Html.AntiForgeryToken()

<div class="form-horizontal">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        <div class="col-lg-12 col-12">
            @Html.EditorFor(model => model.EMail, new { htmlAttributes = new { @class = "form-control", placeholder = "EMail", @id = "inputemail" } })
            @Html.ValidationMessageFor(model => model.EMail, "", new { @class = "text-danger", @id = "dangeremail" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-lg-12 col-12">
            @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", placeholder = "Passwort", @id = "inputpassword" } })
            @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger", @id = "dangerpassword" })
        </div>
    </div>
</div>

因此,它在从表单发布中获取数据后更新了模态主体-您定义了要在AjaxOptions中更新的ID,如上面的代码片段所示。