Passing image from modal to controller - c#

I have the following application, where I have to upload an image directly from modal to the page.
Note that:
The image is already uploaded by the admin to this modal.
The images are saved in "static" file in "wwwroot" folder. So, No database is required for this step.
All what I need is when I click in the image in the modal, it should be uploaded to the view. So, I can save it later in the database.
Here is Image Bank Controller
public IActionResult Index()
{
var webRoot = _hostingEnvironment.WebRootPath;
var appData = System.IO.Path.Combine(webRoot, "static");
var files = Directory.GetFiles(appData, "*.*", SearchOption.AllDirectories);
var model = new ImageBankViewModel()
{
ImagesListUrls = files.Select(i=>Path.GetFileName(i))
};
return View(model);
}
[HttpPost]
public IActionResult Upload(ImageBankViewModel model)
{
if (ModelState.IsValid)
{
if (model.Image != null)
{
string webRootPath = _hostingEnvironment.WebRootPath;
var path = Path.Combine(webRootPath, "static");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var extension = Path.GetExtension(model.Image.FileName);
var newFileName = model.Type + "-" + DateTime.Now.Ticks;
using (var filesStream = new FileStream(Path.Combine(path, newFileName + extension), FileMode.Create))
{
model.Image.CopyTo(filesStream);
}
return RedirectToAction("Index");
}
}
ImageBankViewModel modelVM = new ImageBankViewModel()
{
Image = model.Image,
ImagesListUrls = model.ImagesListUrls,
Type = model.Type
};
return RedirectToAction("Index",modelVM);//Unsuccessful Upload , fix invalid model
}
public IActionResult CreateStory()
{
return View();
}
public ActionResult GetImagesPartial()
{
var webRoot = _hostingEnvironment.WebRootPath;
var appData = System.IO.Path.Combine(webRoot, "static");
var files = Directory.GetFiles(appData, "*.*", SearchOption.AllDirectories);
var model = new ImageBankViewModel()
{
ImagesListUrls = files.Select(i => Path.GetFileName(i))
};
return PartialView("_ImagesBankModal",model);
}
public void ImageDelete(string image)
{
}
public void SelectImage(string image)
{
// Here I want to get the selected image from the modal
}
}
}
Create Story View
#{
ViewData["Title"] = "CreateStory";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>CreateStory</h1>
<div class="row">
<div class="col-md-1">
<label>Pic1</label>
</div>
<div class="col-md-8">
<input type="file" accept="image/*" class="form-control" />
</div>
<div class="col-md-3">
<a class="btn btn-outline-dark" asp-area="" asp-controller="Bank" asp-action="GetImagesPartial" data-toggle="modal" data-target="#myModal" id="sel">Select from image bank</a>
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div id="partial"></div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-1">
<label>Pic2</label>
</div>
<div class="col-md-8">
<input type="file" accept="image/*" class="form-control" />
</div>
<div class="col-md-3">
<button class="btn btn-outline-dark">Select from image bank</button>
</div>
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$('#sel').click(function () {
var route = '#Url.Action("GetImagesPartial", "Bank")';
$('#partial').load(route);
});
});
</script>
}
Modal Partial View
#model TestApplication.Models.ViewModels.ImageBankViewModel
<div class="modal-header">
<h2 class="modal-title">Choose</h2>
</div>
<div class="modal-body">
#if (Model.ImagesListUrls.Any())
{
<table>
#foreach (var image in Model.ImagesListUrls)
{
<tr>
<td>
<a asp-area="" asp-controller="Bank" asp-action="SelectImage" asp-route-image="#image" class="btn btn-light position-absolute" style="right:0">Select</a>
<img src="~/static/#image" class="img-thumbnail" />
</td>
</tr>
}
</table>
}
else
{
<h5>no images exists...</h5>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Cancel</button>
</div>

You can store the relative path of the selected picture in an input and pass them to the action.
The following is an example, you can refer to it.
Index
<form asp-action="Upload" asp-controller="ImageBank" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-1">
<label>Pic1</label>
</div>
<div class="col-md-8">
<input type="file" accept="image/*" class="form-control" name="model.Image"/>
<ul class="selectedpic">
</ul>
</div>
<div class="col-md-3">
<a class="btn btn-outline-dark sel">Select from image bank</a>
</div>
<div class="col-md-8 addedimg">
</div>
</div>
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div id="partial"></div>
</div>
</div>
</div>
<button type="submit">submit</button>
</form>
#section Scripts{
<script type="text/javascript">
var currentsel="";
$('body').on("click",".sel",function () {
localStorage.setItem("currentsel",$(this).attr("class"));
var route = '#Url.Action("GetImagesPartial", "ImageBank")';
$("#myModal").modal("show");
$('#partial').load(route);
});
$('body').on("click",".selectbtn",function () {
var currenttd=$(this).closest("td");
console.log(currenttd.find("img").attr("src"))
var classarry=localStorage.getItem("currentsel").split(" ");
var currentsel="."+classarry[classarry.length-1];
var currentaddedimg=$(currentsel).closest(".row").find(".addedimg");
var addsrc=currenttd.find("img").attr("src");
if(checkisexsist(currentaddedimg,addsrc)){
$(currentsel).closest(".row").find(".selectedpic").append("<li>"+addsrc+"</li>");
$(currentsel).closest(".row").find(".addedimg").append("<input hidden name='selimages' value='"+addsrc+"'/>");
$("#myModal").modal("hide");
$('#myModal').on('hidden.bs.modal', function (e) {
localStorage.removeItem("currentsel");
});
}else{
alert("has selected");
}
});
function checkisexsist(currentaddedimg,addsrc){
var flag=true;
$.each(currentaddedimg.find("input[name='selimages']"), function( index, value ) {
if($(value).val()==addsrc){
flag=false;
}
});
return flag;
}
</script>
}
Controller
[HttpPost]
public IActionResult Upload(ImageBankViewModel model,List<string> selimages)
{
if (ModelState.IsValid)
{
if (model.Image != null)
{
string webRootPath = _hostingEnvironment.WebRootPath;
var path =Path.Combine(webRootPath, "static");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var extension = Path.GetExtension(model.Image.FileName);
var newFileName = model.Type + "-" + DateTime.Now.Ticks;
using (var filesStream = new FileStream(Path.Combine(path, newFileName + extension), FileMode.Create))
{
model.Image.CopyTo(filesStream);
}
}
if(selimages!=null& selimages.Count != 0)
{
string webRootPath = _hostingEnvironment.WebRootPath;
var path = Path.Combine(webRootPath, "static");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
selimages.ForEach(m =>
{
var newFileName = Guid.NewGuid().ToString();
var extension = "." + m.Split(".")[m.Split(".").Length - 1];
var oldpath =webRootPath+m.Replace("/", "\\"); var newpath = Path.Combine(path, newFileName + extension);
System.IO.File.Copy(oldpath,newpath);
});
}
return RedirectToAction("Index");
}
ImageBankViewModel modelVM = new ImageBankViewModel()
{
Image = model.Image,
ImagesListUrls = model.ImagesListUrls,
Type = model.Type
};
return RedirectToAction("Index", modelVM);//Unsuccessful Upload , fix invalid model
}
_ImagesBankModal(Only give the modified place)
<a class="btn btn-light position-absolute selectbtn">Select</a>
Result

Related

Downloading Image in asp.net mvc

Hello i have button and when i click it this function is called :
public async Task<IActionResult> QrCode(int Id)
{
var model = await context.Files.Where(x => x.Id == Id).FirstOrDefaultAsync();
string qrUrl = CreateQrLink(Id);
FileDetailsViewModel fileDetails = new FileDetailsViewModel
{
Id = model.Id,
Name = model.Name,
Author=model.Author,
Description=model.Description,
Genre=model.Genre,
PublishedOn = model.PublishedOn,
QrUrl = qrUrl
};
return View(fileDetails);
}
Here is CreateQrLink function
public string CreateQrLink(int Id)
{
var baseUrl = string.Format("{0}://{1}{2}",Request.Scheme, Request.Host, Url.Content("~"));
QRCodeGenerator QrGenerator = new QRCodeGenerator();
var url = Url.Action("DownloadFileFromFileSystem", "Files", new { id = Id });
QRCodeData QrCodeInfo = QrGenerator.CreateQrCode(baseUrl+url, QRCodeGenerator.ECCLevel.Q);
QRCode QrCode = new QRCode(QrCodeInfo);
Bitmap QrBitmap = QrCode.GetGraphic(60);
byte[] BitmapArray;
using(MemoryStream ms = new MemoryStream())
{
QrBitmap.Save(ms, ImageFormat.Png);
BitmapArray = ms.ToArray();
}
string qrUri= string.Format("data:image/png;base64,{0}", Convert.ToBase64String(BitmapArray));
return qrUri;
}
And Here is View i want to download Image from this view with clicking Download QrCode button,how i can implement it ? I dont save QrLink in database should i save it or something else ? I want to fetch photo from src=Model.QrUrl
#model FileDetailsViewModel
#{
ViewBag.Title = "Qr Code";
}
<div class="row justify-content-center m-3">
<div class="col-sm-8">
<div class="card">
<div class="card-header">
<h1>#Model.Name</h1>
<h2>Product Id: #Model.Id</h2>
</div>
<div class="card-body text-center">
<img style="width:450px;height:450px;" src="#Model.QrUrl" />
</div>
<div class="card-footer text-center">
<a asp-controller="files" asp-action="Details" asp-route-id="#Model.Id" class="btn btn-primary">Back</a>
Download QrCode
</div>
</div>
</div>
</div>
Your returning type should be of FileResult as follow i.e.
string filePath = string.Format("data:image/png;base64,{0}", Convert.ToBase64String(BitmapArray))
string contentType = ImageFormat.Png.ToString();
FileResult qrUri= this.File(filePath, contentType);
return qrUri;
Here is solution just simple add download = "Name for downloaded file" href="url of the image"
<a download="#Model.Name" style="width:150px;" href="#Model.QrUrl"class="btn btn-success">Download</a>

How To Pass Submit Button Value To Controller Action Parameter?

I am trying to save data and edit that data using the button with Id btnSaveAnContinue. Now, whenever I click on Save And Continue button to save data, the command parameter in post method i.e gets Saveandcontinue which is defined in the button as per required.
But whenever, I try to edit the data and save it by clicking on same button, the command parameter in AddEdit POST method does not get Saveandcontinue, it is null.
The View:
<form asp-controller="Doctor" asp-action="AddEdit" method="post" class="form-horizontal" id="DoctorAddEdit" role="form">
#Html.HiddenFor(c => c.DoctorId)
<div class="m-b-md heading-tp-cls">
<h3 class="m-b-none pull-left">Doctor Information <small id="currentUsersInCase"></small></h3>
<div class="doc-buttons pull-right relative">
<button type="submit" class="btn btn-s-md btn-success saveButton" id="btnSave"><i class="fa fa-save fa-fw"></i>Save And Close</button>
<button type="submit" name="command" value="Saveandcontinue" id="btnSaveAnContinue" class="btn btn-s-md btn-success saveButton "><i class="fa fa-save fa-fw"></i>Save And Continue</button>
</div>
<div class="clearfix"></div>
</div>
<section class="panel panel-default tp-section-cls no-left-right-borders" style="padding-top: 10px;">
<div class="row m-l-none m-r-none bg-light lter">
<section>
<div class="col-lg-2 col-md-2 col-sm-6 error-holder-form hideSubject" id="claimanatFirstNameDiv">
<label>First Name<span class="requAstrik">*</span></label>
<input asp-for="FirstName" id="DFirstName" class="form-control subjectHide" placeholder="" type="text">
<span asp-validation-for="FirstName" class="text-danger error"></span>
</div>
<div class="col-lg-2 col-md-2 col-sm-6 hideSubject" id="claimanatMiddleInitialDiv">
<label>Middle Name</label>
<input asp-for="MiddleInitial" id="DMidName" class="form-control subjectHide" placeholder="" type="text">
</div>
</section>
</div>
</section>
</form>
GET method for AddEdit:
public IActionResult AddEdit(int id = 0, bool flag = false)
{
var getDoctorById = _doctorService.GetDoctorInfoById(id);
return View(getDoctorById);
}
POST method for AddEdit:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddEdit(DoctorInfoModel doctorInfo, string command)
{
bool isAjaxCall = HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
if (isAjaxCall)
{
return Content("Saved");
}
if (ModelState.IsValid)
{
var result = 0;
int userId = User.GetUserId();
doctorInfo.CreatedBy = userId;
var saveAndGetUserId = 0;
if (doctorInfo.DoctorId == 0)
{
saveAndGetUserId = _doctorService.SaveUserInfo(doctorInfo);
var user = new ApplicationUser { UserName = doctorInfo.UserName, Email = doctorInfo.DocEmail, UserId = saveAndGetUserId };
var getResult = await _userManager.CreateAsync(user, doctorInfo.Password);
_doctorService.SaveUserRole(user.Id);
}
else
{
var getUserId = _doctorService.GetUser(doctorInfo);
var user = _userManager.Users.FirstOrDefault(c => c.UserId == getUserId);
user.UserName = doctorInfo.UserName;
user.Email = doctorInfo.DocEmail;
if (doctorInfo.Password != null && !"Password#123".Equals(doctorInfo.Password))
{
user.PasswordHash = _userManager.PasswordHasher.HashPassword(user, doctorInfo.Password);
}
try
{
var result1 = await _userManager.UpdateAsync(user);
}
catch (Exception ex)
{
throw;
}
}
var getSaveResult = _doctorService.SaveDoctor(doctorInfo, saveAndGetUserId);
if (getSaveResult.Id > 0)
{
Success(getSaveResult.MessageBody);
}
else
{
Warning(getSaveResult.MessageBody);
}
if (command == "Saveandcontinue")
{
return RedirectToAction(nameof(DoctorController.AddEdit), new { id = getSaveResult.Id, flag = true });
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Doctor");
}
}
Warning("Failed to save Doctor, try again later.");
return View("AddEdit", doctorInfo);
}

Pass data to another page form totally filled asp.net full

I have a problem, I dont get send my data to another page, basically
I need click on date-item link and pass data to another page form filled with data from the first page:
#model List<PontoWeb.Models.Ponto>
#{
ViewBag.Title = "Relatório de Ponto";
ViewBag.MesAtual = System.DateTime.Now.Month;
}
<h2>#ViewBag.Title</h2>
<div class="container-fluid">
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>#Html.ActionLink("Marcar Ponto", "MarcarPonto")</li>
<li>#Html.ActionLink("Ir para Mês Anterior", "MostraPontoMesAnterior",new { ViewBag.MesAgora})</li>
<li>#Html.ActionLink("Ir para Próximo Mês", "MostraPontoMesFuturo", new { ViewBag.MesAgora })</li>
</ul>
</div>
</div>
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<th>Data</th>
<!-- <th>Dia da Semana</th> -->
<th>Entrada</th>
<th>Saída Almoço</th>
<th>Entrada Almoço</th>
<th>Saída</th>
<th>Saldo Diário</th>
<th>Saldo Acumulado</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#Html.ActionLink(item.Data, "MarcarPonto", new { data = item.Data, #entrada = item.Entrada, saida_almoco = item.Saida_Almoco, entrada_almoco = item.Entrada_Almoco, saida = item.Saida }) </td>
<td>#item.Entrada </td>
<td>#item.Saida_Almoco</td>
<td>#item.Entrada_Almoco </td>
<td>#item.Saida</td>
<td>#item.Saldo_Dia</td>
<td>#item.Saldo_Acumulado</td>
</tr>
}
</tbody>
</table>
</div>
to This page
#{
ViewBag.Title = "Marcar Ponto";
}
<div class="container">
<h2>Marcador de Ponto Diário</h2>
<div class="container-fluid">
<div class="row">
<ul>
<li>#Html.ActionLink("Ir para Ponto", "MostraPonto")</li>
</ul>
</div>
</div>
<form class="form" action="/Ponto/Marcar">
<div class="form-group">
<label for="data">Data:</label>
<input type="date" class="form-control" id="data" name="data" value="data">
</div>
<div class="form-group">
<label for="entrada">Entrada:</label>
<input type="time" class="form-control" id="entrada" name="entrada" value="00:00" max="23:59">
</div>
<div class="form-group">
<label for="saida_almoco">Saída Almoço:</label>
<input type="time" class="form-control" id="saida_almoco" name="saida_almoco" value="00:00" max="23:59">
</div>
<div class="form-group">
<label for="entrada_almoco">Entrada Almoço:</label>
<input type="time" class="form-control" id="entrada_almoco" name="entrada_almoco" value="00:00" max="23:59">
</div>
<div class="form-group">
<label for="saida">Saída:</label>
<input type="time" class="form-control" id="saida" name="saida" value="00:00" max="23:59">
</div>
<button type="submit" class="btn btn-default">Gravar</button>
</form>
</div>
<script>
document.getElementById('data').valueAsDate = new Date();
</script>
My controller:
using PontoWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PontoWeb.Controllers
{
public class PontoController : Controller
{
// GET: Ponto
public ActionResult Index()
{
return View();
}
public ActionResult MostraPonto() {
Operacoes operacoes = new Operacoes();
int MesCorrente= DateTime.Now.Month;
ViewBag.MesAgora = MesCorrente;
return View(operacoes.Select(MesCorrente));
}
public ActionResult MarcarPonto() {
return View();
}
// [Route("MarcarPonto/{data}")]
public ActionResult MarcarPontoDados(string data, DateTime entrada, DateTime saida_almoco, DateTime entrada_almoco, DateTime saida)
{
Operacoes op = new Operacoes();
ViewBag.Ponto.Data = op.SelectData(data);
//ViewBag.Ponto.Data = data;
//ViewBag.Ponto.Entrada = entrada;
//ViewBag.Ponto.Saida_Almoco = saida_almoco;
//ViewBag.Ponto.Entrada_Almoco = entrada_almoco;
//ViewBag.Ponto.Saida = saida;
return View("MarcarPonto");
}
public ActionResult Marcar( string data, DateTime entrada, DateTime saida_almoco, DateTime entrada_almoco, DateTime saida ) {
Ponto ponto = new Ponto();
ponto.Data = data ;
ponto.Entrada = entrada.Hour.ToString("00.##") + ":" + entrada.Minute.ToString("00.##");
ponto.Saida_Almoco = saida_almoco.Hour.ToString("00.##") + ":" + saida_almoco.Minute.ToString("00.##");
ponto.Entrada_Almoco = entrada_almoco.Hour.ToString("00.##") + ":" + entrada_almoco.Minute.ToString("00.##");
ponto.Saida = saida.Hour.ToString("00.##") + ":" + saida.Minute.ToString("00.##");
Operacoes operacoes = new Operacoes();
operacoes.Add(ponto);
return Redirect("MostraPonto");
}
public ActionResult MostraPontoMesAnterior(int MesAgora) {
Operacoes operacoes = new Operacoes();
int MesAnterior = MesAgora - 1;
ViewBag.MesAgora = MesAnterior;
return View("MostraPonto",operacoes.Select(MesAnterior));
}
public ActionResult MostraPontoMesFuturo(int MesAgora)
{
Operacoes operacoes = new Operacoes();
int MesFuturo = MesAgora + 1;
ViewBag.MesAgora = MesFuturo;
return View("MostraPonto", operacoes.Select(MesFuturo));
}
}
}
I need get from page1
<td>#Html.ActionLink(item.Data, "MarcarPonto", new { data = item.Data, #entrada = item.Entrada, saida_almoco = item.Saida_Almoco, entrada_almoco = item.Entrada_Almoco, saida = item.Saida }) </td>
To page2 filled.
x-x-x-x-x-x-x-x-x--x-x-x-x-x-x-x-x-x-x-x--x-x
x-x-x-x-x-x-x-x-x--x-x-x-x-x-x-x-x-x-x-x--x-x
x-x-x-x-x-x-x-x-x--x-x-x-x-x-x-x-x-x-x-x--x-x
x-x-x-x-x-x-x-x-x--x-x-x-x-x-x-x-x-x-x-x--x-x

How to insert json message in modal with asp.net mvc

I'm developing a system in .NET and I need to send a json controller msg to the view and show it in modal.
The user will import a spreadsheet and the spreadsheet will be inserted in the database, at the end of the modal it should appear with the message whether it was sent or not.
Or backend is already working.
 
I need help on the front because when I import, it loads a new page with
["Sent with success"]
(the messages are in portuguese) = ["Enviado com sucesso"]
Follows the controller code.
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);
}
}
my view code
<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>
You should not return JSON, as you are performing a full page postback. Instead, you should return a View.
If you do not want to perform a full page postback, you want to use Ajax since the beginning of the request.
For example,
View
Please make sure button is type="button" to avoid full page postback.
#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>
Action Method
[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.");
}
}
Source: File Upload Through JQuery AJAX In ASP.NET MVC

MVC modal popup from partial view - not working

I'm developing an MVC webpage, where I'm intending to do Create and Edit operations via a pop-up. So, the idea is I click on the 'Create' button, a modal-popup appears with all the model fields empty and allows user to input. In the same way, when user double clicks on any row, the row would open up for edit via the same pop-up, this time with the details filled from that row.
So, for reusage, I have decided to develop a single partial view(that would be the pop-up) and accept 'Model' as input.
My problem is, no matter what I do, I'm not able to make the partial view come up as pop-up. (Note: my main parent Index view would accpet input as List
Here is my code:
MY Index view:
#model List<TrackBuildConfig.DAL.Models.BuildModel>
#{
Layout = null;
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/MyScript.js" type="text/javascript"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="jumbotron">
<h1>Track Coverity and Nightly builds</h1>
<h4>on your own!</h4>
</div>
<div class="container-fluid">
<div class="row btn-group">
#Html.ActionLink("Create a new record", "SaveData", "Home", new { configID = 0 }, new { #class = "btn btn-primary modal-link", id = "btnCreate"})
</div>
<div class="modal fade" aria-labelledby="ModalLabel" id="modal-container" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content" style="width: 500px !important; margin:10px !important">
</div>
</div>
</div>
</div>
</body>
</html>
Script:
$(function () {
$('body').on('click', '.modal-link', function (e) {
e.preventDefault();
$('#btnCreate').attr('data-toggle', 'modal');
$('#btnCreate').attr('data-target', '#modal-container');
$('#modal-container').modal('show');
return true;
});
}
});
Partial view _PartialModal.csHtml
#model TrackBuildConfig.DAL.Models.BuildModel
#{
Layout = null;
}
<html>
<head>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/MyScript.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="">
<div class="modal-header">
<button type="button" class="close" aria-hidden="true" data-dismiss="modal">&times</button>
<h4>Configure Coverity and Nightly builds</h4>
</div>
<div class="modal-body" style="height: 400px;">
#using (Html.BeginForm("SaveData", "Home", FormMethod.Post))
{
<div class="row">
<div class="form-group row">
<div class="col-sm-4">
#Html.Label("Stream name", new { #class = "control-label" })
</div>
<div class="col-sm-6">
#Html.DropDownList("BuildLocations", (IEnumerable<SelectListItem>)ViewBag.BuildLocations, new { #class = "col-sm-6 form-control", id = "ddlBuildLocation" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
#Html.Label("Build Location", new { #class = "control-label" })
</div>
<div class="col-sm-6">
#Html.DropDownList("Streams", (IEnumerable<SelectListItem>)ViewBag.Streams, new { #class = "col-sm-6 form-control", id = "ddlStreams" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.IsCoverity)
Enable Coverity
</label>
</div>
</div>
<div class="col-sm-8">
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.IsNightly)
Enable Nightly build
</label>
</div>
</div>
<label style="color: red; font-weight: 300;" id="warningEnableBuild"></label>
</div>
<div class="form-group row">
#Html.Label("Email for Coverity", new { #class = "col-sm-4 control-label" })
<div class="col-sm-8" style="width: 100%">
#Html.TextAreaFor(m => m.EmailCoverity, new { #class = "form-control clsEmailCoverity", #placeholder = "Enter some value", #onkeyup = "return true;", #rows = "5", id = "txtEmailCoverity" })
#*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*#
<span class="help-block">Please add only comma separated addresses!</span>
<label style="color: red; font-weight: 300;" id="warningLabelCoverity"></label>
</div>
</div>
<div class="form-group row">
#Html.Label("Email for Nightly", new { #class = "col-sm-4 control-label" })
<div class="col-sm-8" style="width: 100%">
#Html.TextAreaFor(m => m.EmailNightly, new { #class = "form-control clsEmailNightly", #placeholder = "Enter some value", #onkeyup = "return true;", #rows = "5", id = "txtEmailNightly" })
#*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*#
<span class="help-block">Please add only comma separated addresses!</span>
<label style="color: red; font-weight: 300;" id="warningLabelNightly"></label>
</div>
</div>
<div class="modal-footer">
<button id="btnSave" class="btn btn-success" type="submit" role="button">Save changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
}
</div>
</div>
</body>
</html>
Controller methods:
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
GetData getdata = new GetData();
return View(getdata.GetDataFromTable());
}
[HttpPost]
public ActionResult SaveData()
{
return View("Index");
}
//[HttpGet]
public ActionResult SaveData(int configID)
{
BuildModel model = new BuildModel();
PopulateBuildLocations();
PopulateStreams();
//Create
if (configID != 0)
{
GetData getdata = new GetData();
model = getdata.GetDataFromTable().Where(co => co.ConfigID == configID).FirstOrDefault();
}
else
{
model.BuildLocation = "";
model.EmailCoverity = "";
model.EmailNightly = "";
model.IsCoverity = false;
model.IsNightly = false;
}
return PartialView("_PartialModal", model);
}
public void PopulateBuildLocations()
{
string reportTypes = ConfigurationManager.AppSettings["ddlStreams"].ToString();
ViewBag.BuildLocations = reportTypes.Split('|')
.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
}
public void PopulateStreams()
{
List<string> lstStreams = new List<string>();
for (int i = 0; i < 6; i++)
{
lstStreams.Add("Stream " + i);
}
ViewBag.Streams = lstStreams.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
}
}
This is the link I used as reference. Reference
Please put my code in your visual studio and see that it works.
Controller/View Model/Classes:
public class BuildModel
{
public string theBuildModel { get; set; }
public int ConfigID { get; set; }
public string BuildLocation { get; set; }
public string EmailCoverity { get; set; }
public string EmailNightly { get; set; }
public bool IsCoverity { get; set; }
public bool IsNightly { get; set; }
}
public class GetData
{
public IList<BuildModel> GetDataFromTable()
{
IList<BuildModel> list = new List<BuildModel>();
var buildModel1 = new BuildModel { theBuildModel = "one" };
var buildModel2 = new BuildModel { theBuildModel = "two" };
var buildModel3 = new BuildModel { theBuildModel = "three" };
list.Add(buildModel1);
list.Add(buildModel2);
list.Add(buildModel3);
return list;
}
}
public class HomeController : Controller
{
[HttpPost]
public ViewResult SaveData(BuildModel buildModel)
{
GetData getdata = new GetData();
var model = getdata.GetDataFromTable();
return View("IndexStackOverflow", model);
}
[HttpGet]
public PartialViewResult SaveData(int configID)
{
BuildModel model = new BuildModel();
PopulateBuildLocations();
PopulateStreams();
//Create
if (configID != 0)
{
GetData getdata = new GetData();
model = getdata.GetDataFromTable().Where(co => co.ConfigID == configID).FirstOrDefault();
}
else
{
model.BuildLocation = "";
model.EmailCoverity = "";
model.EmailNightly = "";
model.IsCoverity = false;
model.IsNightly = false;
}
return PartialView("_PartialModal", model);
}
public void PopulateBuildLocations()
{
string reportTypes = ConfigurationManager.AppSettings["ddlStreams"].ToString();
ViewBag.BuildLocations = reportTypes.Split('|')
.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
}
public void PopulateStreams()
{
List<string> lstStreams = new List<string>();
for (int i = 0; i < 6; i++)
{
lstStreams.Add("Stream " + i);
}
ViewBag.Streams = lstStreams.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
}
public ActionResult IndexStackOverflow()
{
GetData getdata = new GetData();
return View(getdata.GetDataFromTable());
}
web.config:
<appSettings>
<add key="ddlStreams" value="text1|value1"/>
</appSettings>
View:
#model List<Testy20161006.Controllers.BuildModel>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexStackOverflow</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
#*YOU MUST PUT THE NEXT LINE FOLLOWING IN YOUR CODE-NUGET IF YOU NEED TO GET THE SCRIPT*#
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<div class="jumbotron">
<h1>This is part of the Main Page</h1>
<h1>Partial View rendered in result</h1>
<h1>Track Coverity and Nightly builds</h1>
<h4>on your own!</h4>
</div>
<div class="container-fluid">
<div class="row btn-group">
#*#Html.ActionLink("Create a new record", "SaveData", "Home", new { configID = 0 },
new { #class = "btn btn-primary modal-link", id = "btnCreate" })*#
#using (Ajax.BeginForm("SaveData", "Home", new { configID = 0 },
new AjaxOptions
{
UpdateTargetId = "result",
InsertionMode = InsertionMode.Replace,
OnFailure = "error",
HttpMethod = "Get"
}))
{
<input id="btnCreate" type="submit" value="Create a new record" class="btn btn-primary modal-link" />
}
<div id="result"></div>
</div>
</div>
</body>
</html>
Partial View in shared folder:
#model Testy20161006.Controllers.BuildModel
<script type="text/javascript">
$(function () {
$('#myModal').modal('show');
})
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Configure Coverity and Nightly builds</h4>
</div>
<div class="modal-body">
<div class="modal-body" style="height: 400px;">
#using (Html.BeginForm("SaveData", "Home", FormMethod.Post))
{
<div class="row">
<div class="form-group row">
<div class="col-sm-4">
#Html.Label("Stream name", new { #class = "control-label" })
</div>
<div class="col-sm-6">
#Html.DropDownList("BuildLocations", (IEnumerable<SelectListItem>)ViewBag.BuildLocations, new { #class = "col-sm-6 form-control", id = "ddlBuildLocation" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
#Html.Label("Build Location", new { #class = "control-label" })
</div>
<div class="col-sm-6">
#Html.DropDownList("Streams", (IEnumerable<SelectListItem>)ViewBag.Streams, new { #class = "col-sm-6 form-control", id = "ddlStreams" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.IsCoverity)
Enable Coverity
</label>
</div>
</div>
<div class="col-sm-8">
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.IsNightly)
Enable Nightly build
</label>
</div>
</div>
<label style="color: red; font-weight: 300;" id="warningEnableBuild"></label>
</div>
<div class="form-group row">
#Html.Label("Email for Coverity", new { #class = "col-sm-4 control-label" })
<div class="col-sm-8" style="width: 100%">
#Html.TextAreaFor(m => m.EmailCoverity, new { #class = "form-control clsEmailCoverity", #placeholder = "Enter some value", #onkeyup = "return true;", #rows = "5", id = "txtEmailCoverity" })
#*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*#
<span class="help-block">Please add only comma separated addresses!</span>
<label style="color: red; font-weight: 300;" id="warningLabelCoverity"></label>
</div>
</div>
<div class="form-group row">
#Html.Label("Email for Nightly", new { #class = "col-sm-4 control-label" })
<div class="col-sm-8" style="width: 100%">
#Html.TextAreaFor(m => m.EmailNightly, new { #class = "form-control clsEmailNightly", #placeholder = "Enter some value", #onkeyup = "return true;", #rows = "5", id = "txtEmailNightly" })
#*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*#
<span class="help-block">Please add only comma separated addresses!</span>
<label style="color: red; font-weight: 300;" id="warningLabelNightly"></label>
</div>
</div>
<div class="modal-footer">
<button id="btnSave" class="btn btn-success" type="submit" role="button">Save changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
}
</div>
</div>
</div>
</div>
</div>

Categories