c# - 如何使用 asp.net mvc 在模态中插入 json 消息

标签 c# asp.net json asp.net-mvc

我正在 .NET 中开发一个系统,我需要向 View 发送一个 json Controller 消息并以模式显示它。

用户将导入一个电子表格,该电子表格将被插入到数据库中,在模式的末尾,无论是否已发送,它都应该与消息一起出现。

或者后端已经在工作。 我需要前面的帮助,因为当我导入时,它会加载一个新页面

["发送成功"]

(消息是葡萄牙语)= ["Enviado com sucesso"]

遵循 Controller 代码。

public JsonResult UploadExcel(HttpPostedFileBase FileUpload)
    {

        List<string> data = new List<string>();
        if (FileUpload != null)
        {
            // tdata.ExecuteCommand("truncate table OtherCompanyAssets");  
            if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                string filename = FileUpload.FileName;
                string targetpath = "C:/Users/70561/Documents";
                FileUpload.SaveAs(targetpath + filename);
                string pathToExcelFile = targetpath + filename;
                var connectionString = "";
                if (filename.EndsWith(".xls"))
                {
                    connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
                }
                else if (filename.EndsWith(".xlsx"))
                {
                    connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
                }

                var adapter = new OleDbDataAdapter("SELECT * FROM [Planilha1$]", connectionString);
                var ds = new DataSet();

                adapter.Fill(ds, "ExcelTable");

                DataTable dtable = ds.Tables["ExcelTable"];

                string sheetName = "Planilha1";

                var excelFile = new ExcelQueryFactory(pathToExcelFile);
                var dados = from a in excelFile.Worksheet<RETORNO_CM>(sheetName) select a;

                foreach (var a in dados)
                {
                    try
                    {
                        if (a.CM_CODIGO != null && a.CM_QM_COMPONENTE_RMA != null && a.CM_NS != null && a.CM_DESCRICAO != null &&
                            a.CM_DEFEITO != null && a.J_FALHA != null &&
                            a.CM_TIPO_DEFEITO != null && a.J_PLACA_RETRABALHO != null &&
                            a.J_PLACA_RESTESTADA != null && a.J_STATUS != null && a.CM_NOME_TESTE != null && a.CM_NOME_DEBUG != null)
                        {
                            RETORNO_CM CM = new RETORNO_CM();
                            CM.CM_CODIGO = a.CM_CODIGO;
                            CM.CM_QM_COMPONENTE_RMA = a.CM_QM_COMPONENTE_RMA;
                            CM.CM_NS = a.CM_NS;
                            CM.CM_DESCRICAO = a.CM_DESCRICAO;
                            CM.CM_DATA_REPARO = a.CM_DATA_REPARO;
                            CM.CM_DEFEITO = a.CM_DEFEITO;
                            CM.J_FALHA = a.J_FALHA;
                            CM.CM_TIPO_DEFEITO = a.CM_TIPO_DEFEITO;
                            CM.CM_COMPONENTE = a.CM_COMPONENTE;
                            CM.J_PLACA_RETRABALHO = a.J_PLACA_RETRABALHO;
                            CM.J_PLACA_RESTESTADA = a.J_PLACA_RESTESTADA;
                            CM.J_STATUS = a.J_STATUS;
                            CM.CM_NOME_TESTE = a.CM_NOME_TESTE;
                            CM.CM_NOME_DEBUG = a.CM_NOME_DEBUG;
                            db.RETORNO_CM.Add(CM);

                            db.SaveChanges();
                        }
                        else
                        {
                            data.Add("<ul>");

                            data.Add("</ul>");
                            data.ToArray();
                            return Json(data, JsonRequestBehavior.AllowGet);
                        }
                    }

                    catch (DbEntityValidationException ex)
                    {
                        foreach (var entityValidationErrors in ex.EntityValidationErrors)
                        {

                            foreach (var validationError in entityValidationErrors.ValidationErrors)
                            {
                                Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
                            }
                        }
                    }
                }
                //deleting excel file from folder  
                if ((System.IO.File.Exists(pathToExcelFile)))
                {
                    System.IO.File.Delete(pathToExcelFile);
                }
                data.Add("Enviado com sucesso");
                return Json(data, JsonRequestBehavior.AllowGet);
            }
            else
            {
                //alert message for invalid file format  
                data.Add("Apenas arquivos excel sao suportados");
                return Json(data, JsonRequestBehavior.AllowGet);
            }
        }
        else
        {
            if (FileUpload == null) data.Add("Selecione um arquivo");
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }

我的查看代码

<div class="box">
<div class="box-body">
    <hr />
    <article class="table-responsive" style="overflow:hidden">
        <p class="lead">Teste de importação.</p>
        <hr />
        @using (Html.BeginForm("UploadExcel", "RetornoCM", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "return myFunction()" }))
        {
            <div class="form-horizontal">
                <div class="form-group">

                    <div class="control-label col-md-2">Escolha o Arquivo:</div>
                    <div class="col-md-10">
                        <input type="file" id="FileUpload" name="FileUpload" class="" />
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Enviar" id="btnSubmit" class="btn btn-primary" />
                    </div>
                </div>
            </div>
        }

        <div class="modal fade" id="myModal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                        <h4 class="modal-title">Modal title</h4>
                    </div>
                    <div class="modal-body">
                        <p>
                            <b>Message:</b><br>
                            <input class="message-edit-text" type="text" size="20">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
    </article>
</div>

最佳答案

您不应返回 JSON,因为您正在执行整页回发。相反,您应该返回一个 View

如果您不想执行完整的页面回发,您希望从请求开始就使用 Ajax

例如,

查看

请确保按钮是 type="button" 以避免整页回发。

@using (Html.BeginForm("UploadExcel", "RetornoCM", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="form-horizontal">
        <div class="form-group">

            <div class="control-label col-md-2">Escolha o Arquivo:</div>
            <div class="col-md-10">
                <input type="file" id="FileUpload" name="FileUpload" class="" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <button type="button" id="btnSubmit" class="btn btn-primary">
                    Enviar
                </button>
            </div>
        </div>
    </div>
}

<script>
    $(function () {
        $('#btnSubmit').click(function() {

            // Checking whether FormData is available in browser
            if (window.FormData !== undefined) {

                var fileUpload = $("#FileUpload").get(0);
                var files = fileUpload.files;

                // Create FormData object
                var fileData = new FormData();

                // Looping over all files and add it to FormData object
                for (var i = 0; i < files.length; i++) {
                    fileData.append(files[i].name, files[i]);
                }

                $.ajax({
                    url: '@Url.Action("UploadExcel", "RetornoCM")',
                    type: "POST",
                    contentType: false, // Not to set any content header
                    processData: false, // Not to process data
                    data: fileData,
                    success: function(result) {
                        alert(result);
                    },
                    error: function(err) {
                        alert(err.statusText);
                    }
                });
            }

        });
    });
</script>

操作方法

[HttpPost]
public ActionResult UploadExcel()
{
    if (Request.Files.Count > 0)
    {
        try
        {
            HttpFileCollectionBase files = Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFileBase file = files[i];
                // Do somethig with file
            }
            return Json("File Uploaded Successfully!");
        }
        catch (Exception ex)
        {
            return Json("Error occurred. Error details: " + ex.Message);
        }
    }
    else
    {
        return Json("No files selected.");
    }
}

来源:File Upload Through JQuery AJAX In ASP.NET MVC

关于c# - 如何使用 asp.net mvc 在模态中插入 json 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45218080/

相关文章:

c# - 多线程应用程序中第 4 个 HttpWebRequest 异常超时

c# - 如果我有一个自定义对话框窗口,每次都可以创建一个新对话框吗?

asp.net - HttpModule 在 IIS 6 上未接收 cookie

json - 无法打开服务器上的 Json 文件

c# - 无法解析 JQuery ajax 调用返回的 JSON

android - org.json.JSONObject在android中无法转换为JSONArray

c# - 如何通过 asp.net mvc 5 中的 actionlink 传递包含连字符的 routeValues

javascript - 获取文档的部分以匹配 HTML 模板

c# - .Net 4.0 JSON 序列化 : Double quotes are changed to\"

javascript - asp.net 下拉列表 - 使用 javascript 填充