C# 如何使用asp.net mvc在模式中插入json消息
我正在.NET中开发一个系统,我需要向视图发送一个json控制器消息,并在模式中显示它 用户将导入电子表格,并将电子表格插入数据库,在模式结束时,无论是否发送,电子表格都应与消息一起显示 或者后端已经在工作。 我需要前面的帮助,因为当我导入时,它会加载一个带有 [“成功发送”] (信息是葡萄牙语)=[“Enviado com sucesso”] 遵循控制器代码C# 如何使用asp.net mvc在模式中插入json消息,c#,asp.net,json,asp.net-mvc,C#,Asp.net,Json,Asp.net Mvc,我正在.NET中开发一个系统,我需要向视图发送一个json控制器消息,并在模式中显示它 用户将导入电子表格,并将电子表格插入数据库,在模式结束时,无论是否发送,电子表格都应与消息一起显示 或者后端已经在工作。 我需要前面的帮助,因为当我导入时,它会加载一个带有 [“成功发送”] (信息是葡萄牙语)=[“Enviado com sucesso”] 遵循控制器代码 public JsonResult UploadExcel(HttpPostedFileBase FileUpload) {
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);
}
}
public JsonResult UploadExcel(HttpPostedFileBase FileUpload)
{
列表数据=新列表();
if(FileUpload!=null)
{
//tdata.ExecuteCommand(“截断表OtherCompanyAssets”);
if(FileUpload.ContentType==“application/vnd.ms excel”| | FileUpload.ContentType==“application/vnd.openxmlformats officedocument.spreadsheetml.sheet”)
{
字符串文件名=FileUpload.filename;
字符串targetpath=“C:/Users/70561/Documents”;
FileUpload.SaveAs(targetpath+filename);
字符串pathToExcelFile=目标路径+文件名;
var connectionString=“”;
if(filename.EndsWith(“.xls”))
{
connectionString=string.Format(“提供程序=Microsoft.Jet.OLEDB.4.0;数据源={0};扩展属性=Excel 8.0;”,pathToExcelFile);
}
else if(filename.EndsWith(“.xlsx”))
{
connectionString=string.Format(“Provider=Microsoft.ACE.OLEDB.12.0;数据源={0};扩展属性=\”Excel 12.0 Xml;HDR=YES;IMEX=1\”;“,pathToExcelFile);
}
var adapter=new-OleDbDataAdapter(“从[Planilha1$]中选择*”,connectionString);
var ds=新数据集();
适配器。填充(ds,“ExcelTable”);
DataTable dtable=ds.Tables[“ExcelTable”];
字符串sheetName=“Planilha1”;
var excelFile=新的ExcelQueryFactory(pathToExcelFile);
var dados=从Excel文件中的a中。工作表(sheetName)选择a;
foreach(护墙板中的var a)
{
尝试
{
如果(a.CM\u CODIGO!=null和&a.CM\u QM\u component\u RMA!=null和&a.CM\u NS!=null和&a.CM\u descripcao!=null&&
a、 CM_DEFEITO!=null和&a.J_FALHA!=null&&
a、 CM_TIPO_DEFEITO!=null和&a.J_PLACA_retbalho!=null&&
a、 J_PLACA_resestada!=null和&a.J_状态!=null和&a.CM_NOME_TESTE!=null和&a.CM_NOME_调试!=null)
{
Returno_CM=新的Returno_CM();
CM.CM_CODIGO=a.CM_CODIGO;
CM.CM_QM_component e_RMA=a.CM_QM_component e_RMA;
CM.CM_NS=a.CM_NS;
CM.CM_descripcao=a.CM_descripcao;
CM.CM_数据_REPARO=a.CM_数据_REPARO;
CM.CM_DEFEITO=a.CM_DEFEITO;
CM.J_FALHA=a.J_FALHA;
CM.CM_TIPO_DEFEITO=a.CM_TIPO_DEFEITO;
CM.CM_分量=a.CM_分量;
CM.J_PLACA_RETRABALHO=a.J_PLACA_RETRABALHO;
CM.J_PLACA_RESTESTADA=a.J_PLACA_RESTESTADA;
CM.J_状态=a.J_状态;
CM.CM_NOME_TESTE=a.CM_NOME_TESTE;
CM.CM_NOME_DEBUG=a.CM_NOME_DEBUG;
db.returno_CM.Add(CM);
db.SaveChanges();
}
其他的
{
数据。添加(“”);
数据。添加(“
”);
data.ToArray();
返回Json(数据,JsonRequestBehavior.AllowGet);
}
}
捕获(DbEntityValidationException ex)
{
foreach(ex.entityValidationErrors中的var entityValidationErrors)
{
foreach(entityValidationErrors.ValidationErrors中的var validationError)
{
写入(“属性:+validationError.PropertyName+”错误:+validationError.ErrorMessage);
}
}
}
}
//从文件夹中删除excel文件
如果((System.IO.File.Exists(pathToExcelFile)))
{
System.IO.File.Delete(pathToExcelFile);
}
添加数据(“Enviado com sucesso”);
返回Json(数据,JsonRequestBehavior.AllowGet);
}
其他的
{
//无效文件格式的警报消息
添加数据(“Apenas arquivos excel sao suportados”);
返回Json(数据,JsonRequestBehavior.AllowGet);
}
}
其他的
{
如果(FileUpload==null)data.Add(“Selecione um arquivo”);
返回Json(数据,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>
进口测试
@使用(Html.BeginForm(“UploadExcel”,“retronocm”,FormMethod.Post,new{enctype=“multipart/formdata”,onsubmit=“return myFunction()”}))
{
埃斯科尔哈·阿奎沃:
@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.");
}
}