I am having trouble binding knockout js viewmodel - c#

when it comes to JavaScript I find it difficult to swallow. I have been trying to bind data from my back end to the client but I haven't been successful. I think Its time for someone to show me my mistakes. here are the codes.
$(".tab a").click(function (e) {
var url = "";
var data = "";
var Item = "";
var test = $(e.target).text();
if(test === '#') {
var url = "#";
}
else if (test === '#') {
var url = "#";
} else if (test === '#') {
var url = '#';
} else if (test === '#') {
url = '#';
}
else {
throw new Error('hello');
}
function userViewmodel() {
var self = this;
 
self.Id = ko.observable("");
self.Link = ko.observable("");
self.Image = ko.observable("");
self.Title = ko.observable("");
self.Ajax = ko.observable("");
getUserInfo();
function getUserInfo() {
$.getJSON("../../Home/tabcontent?=" + url)
.done(function (data) {
self.Id(data.id);
self.Link(data.link);
self.Image(data.image);
self.Title(data.title);
self.Ajax(data.ajax);
});
}
};
ko.applyBindings(new userViewmodel());
});
I am trying to bind to this.
<div class="row col s12" style="margin-top:18px;" id="test-swipe-1">
#foreach (var item in Model)
{
<div class="col s12 m6 l3">
<div class="card z-depth-4">
<div class="card-image waves-effect waves-block waves-light" style="height:350px">
<a href="#Url.Action("Movie", "Home", new {id= #item.id, title= #item.title})">
<img class="activat" src="#item.image">
</a>
</div>
<div class="card-content blue-grey darken-4">
<span class="card-title activator grey-text text-darken-1"><a class="a-title truncate" style="color:inherit">#item.title</a><i class="material-icons right" onclick="loadDoc('#item.id', '#item.ajax')">more_vert</i></span>
<p><a href="#" >Report broken link</a></p>
</div>
<div class="card-reveal blue-grey darken-4">
<span class="card-title grey-text text-darken-1 title-wrap">#item.title<i class="material-icons right">close</i></span>
<div id="#item.id"></div>
</div>
</div>
</div>
}
</div>
I know its in razor view, I left it like that so you can understand how I want the data to be formatted.
please how do I bind the data to the html tags?

Related

Problem with my Jquery function dosent call controllerside method

I have these codes in my Razor which already was working but now it doesn't works:
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Pcode" class="control-label"></label>
<input asp-for="Pcode" class="form-control" id="UserCode" name="UserCode" onchange="UserCheck()" style="background-color:lightyellow" />
<span asp-validation-for="Pcode" class="text-danger"></span>
</div>
<div class="row">
<label class="col-sm-2"></label>
<div class="col-sm-10">
<p id="Status" name="Status" />
</div>
</div>
these are my code in jquery function :
$.noConflict();
function UserCheck()
{
$("#Status").html("Checking ...");
$.post("#Url.Action("CheckIfUserCodeExist", "Leave")",
{
UserCode: $("#UserCode").val(),
},
function (data) {
if (data) {
$("#Status").html(data);
#*$("#Status").html('#TempData["NF"]');*#
$("#UserCode").css("border-color", "Green");
}
else {
$("#Status").html('<font color="Red">این شخص قبلا ثبت نام نشده </font>');
$("#UserCode").css("border-color", "Red");
}
});
}
and here are my code in controller side:
public JsonResult CheckIfUserCodeExist(Int32 UserCode)
{
System.Threading.Thread.Sleep(200);
var SearchData = db.Persons.Where(x => x.Pcode == UserCode).SingleOrDefault();
TempData.Remove("NF");
//TempData.clear();
if (SearchData != null)
{
string N = SearchData.Name;
string F = SearchData.Family;
TempData["code"] = UserCode;
var NF = N + " " + F;
//TempData["NF"] = NF;
return Json(NF);
}
else
{
TempData["code"] = 0;
return Json("");
}
}
would you please help me where is the problem? I tested this several time without error.but now ....

Passing image from modal to controller

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

Load more content in ASP.Net Core and Ajax - any idea

I want to load some element from database and next after click button load more elements. In Controller my code looks like:
public ActionResult GetData(int currentIndex, int elementsNumber)
{
var query = (from restauracja in _context.Restauracja
select restauracja).Skip(currentIndex * elementsNumber)
.Take(elementsNumber).ToList();
var list = JsonConvert.SerializeObject(query,
Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return Content(list, "application/json");
}
In View i have this:
$("#next").click(function () {
GetData();
});
function GetData() {
var currentIndex2 = 1;
var elementsNumber2 = 3;
$.ajax({
type: "POST",
url: 'Restauracja/GetData',
data: { currentIndex: currentIndex2, elementsNumber: elementsNumber2 },
dataType: "json",
success:
error: function () { alert('Niesukces'); },
});
}
Now, in success: i must generate html like this
<div class="box_list isotope-item popular">
<div class="row no-gutters">
<div class="col-lg-5">
<figure>
<small>#item.Kategoria</small>
<a href="#Url.Action("Szczegoly","restauracja", new { id = item.IdRestauracji },
null) ">#if (item.ObrazekWyrozniajacy != null)
{<img src="data:image/jpeg;base64,#Convert.ToBase64String(item.ObrazekWyrozniajacy)"
class="img-fluid" alt="" width="800" height="533">}<div class="read_more">
<span>Sprawdź lokal</span></div></a>
</figure>
</div>
<div class="col-lg-7">
<div class="wrapper">
<h3>#Html.ActionLink(item.NazwaObiektu, "Szczegoly", "Restauracja", new { id = item.IdRestauracji }, null) #item.Ulica #item.NumerLokalu, #item.Miejscowosc</h3>
<p>#item.Zajawka</p>
<span class="price">From <strong>$54</strong> /per person</span>
</div>
<ul>
<li><i class="ti-eye"></i> 164 views</li>
<li><div class="score"><span>Superb<em>350 Reviews</em></span><strong>8.9</strong></div></li>
</ul>
</div>
</div>
</div>
This code is not that bad yet, because I can convert it to html, e.g.:
success: function (data) {
for (var i = 0; i < data.length; i++) {
var encodedString = btoa(data[i].ObrazekWyrozniajacy);
var html = [
'<div class="box_list isotope-item popular">',
'<div class="row no-gutters">',
'<figure>',
'<small>' + data[i].Kategoria + '</small>',
'<a href="#Url.Action("Szczegoly","restauracja", new { id = "-1" }, null) ">',
'#if ("-2" != null){<img src="data:image/jpeg;base64,-3" class="img-fluid" alt="" width="800" height="533" >}',
'<div class="read_more"><span>Sprawdź lokal</span></div></a >',
'</figure >',
'</div>',
'<div class="col-lg-7">',
'<div class="wrapper">',
'',
'<h3>' + data[i].Ulica + data[i].NumerLokalu + data[i].Miejscowosc + '</h3>',
'<p>' + data[i].Zajawka + '</p>',
'<span class="price">From <strong>$54</strong> /per person</span>',
'</div>',
'<ul>',
'<li><i class="ti-eye"></i> 164 views</li>',
'<li><div class="score"><span>Superb<em>350 Reviews</em></span><strong>8.9</strong></div></li>',
'</ul>',
'</div>',
'</div>',
'</div>',
].join("\n");
$(".isotope-wrapper").append(html);
However, in the database I store images in the form of byte []. Can I convert them somehow differently? Or do it differently?
Instead of returning a hard coded html, you can return a partial view as below:
Create the partial view for ajax response:
<!-- RestauracjaPartial.cshtml -->
<!-- Model is the same as the main page -->
#model IndexModel
#foreach(var item in Model)
{
<div class="box_list isotope-item popular">
<div class="row no-gutters">
<div class="col-lg-5">
<figure>
<small>#item.Kategoria</small>
<a href="#Url.Action("Szczegoly","restauracja", new { id = item.IdRestauracji },
null) ">#if (item.ObrazekWyrozniajacy != null)
{<img src="data:image/jpeg;base64,#Convert.ToBase64String(item.ObrazekWyrozniajacy)"
class="img-fluid" alt="" width="800" height="533">}<div class="read_more">
<span>Sprawdź lokal</span></div></a>
</figure>
</div>
<div class="col-lg-7">
<div class="wrapper">
<h3>#Html.ActionLink(item.NazwaObiektu, "Szczegoly", "Restauracja", new { id = item.IdRestauracji }, null) #item.Ulica #item.NumerLokalu, #item.Miejscowosc</h3>
<p>#item.Zajawka</p>
<span class="price">From <strong>$54</strong> /per person</span>
</div>
<ul>
<li><i class="ti-eye"></i> 164 views</li>
<li><div class="score"><span>Superb<em>350 Reviews</em></span><strong>8.9</strong></div></li>
</ul>
</div>
</div>
</div>
}
And modify the backend method as below:
public ICollection<Restauracja> Items { get; set; }
public IActionResult GetData(int currentIndex, int elementsNumber)
{
Items = from restauracja in _context.Restauracja
select restauracja).Skip(currentIndex * elementsNumber)
.Take(elementsNumber).ToList();
return new PartialViewResult()
{
ViewName = "RestauracjaPartial",
ViewData = this.ViewData
};
}

How to get the data-id Send to another controller mvc

How to get the data-id sent to another controller in ASP.NET MVC?
The employee submits the form, automatically determines the id and department position, and then sends it to the manager for approval.
The manager clicks approval or reject on this page, and the form is sent to the next person for approval. At this step, the page prompts that id = null cannot be run. What should I do?
But Google background shows that I got this Id, how to send this Id to action?
public PartialViewResult saveStatus(int id, string Status, string AddDate, string Remark)
{
int approvalId;
if (id == 0 && Session["AppId"] == null)
{
var staff = db.Staffs.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
RequestForApproval ap = new RequestForApproval
{
RequestToStaffId = staff.Id,
RequestDate = DateTime.Now,
};
db.RequestForApprovals.Add(ap);
db.SaveChanges();
Session["AppId"] = ap.ReimbursementID;
approvalId = ap.Id;
}
else
{
approvalId = int.Parse(Session["AppId"].ToString());
}
ApprovalStatus temp = new ApprovalStatus
{
Id = approvalId,
Remark = Remark,
AddDate = DateTime.Now
};
db.ApprovalStatuses.Add(temp);
db.SaveChanges();
var df = db.ApprovalStatuses.Where(s => s.Id == approvalId).ToList();
return PartialView(df);
}
public JsonResult CreateStatus()
{
List<ApprovalStatus> mv = new List<ApprovalStatus>();
if(Session["AppId"] == null)
{
ViewBag.Ae = 0;
}
else
{
ViewBag.Ae = Session["AppId"];
int approvalId = int.Parse(Session["AppId"].ToString());
mv = db.ApprovalStatuses.Where(s => s.Id == approvalId).ToList();
}
return Json(mv);
}
public ActionResult AddRequestForApproval()
{
// var staffUser = db.StaffPositions.Where(a => a.Staff.UserName == System.Web.HttpContext.Current.User.Identity.GetUserId());
var rmid = Session["RmId"].ToString();
if (string.IsNullOrEmpty(rmid))
{
return RedirectToAction("Index");
}
int reimbursementId = int.Parse(rmid);
Session["RmId"] = null;
var Res = db.Reimbursements.Find(reimbursementId);
var managerId = GetByStaffId(Res.StaffId,reimbursementId);
RequestForApproval temp = new RequestForApproval();
temp.ReimbursementID = reimbursementId;
temp.RequestDate = DateTime.Now;
temp.RequestToStaffId = managerId;
db.RequestForApprovals.Add(temp);
db.SaveChanges();
return RedirectToAction("Index");
}
View:
#model Reimbursements.Models.RequesViewModel
#{
ViewBag.Title = "Index";
var add = Session["AppId"];
}
<h2>Index</h2>
<table class="table" id="table1">
<tr>
<th></th>
<th>
Staff Fname
</th>
<th>
RequestDate
</th>
<th></th>
</tr>
#foreach (var item in Model.GetReApproval)
{
<tr>
<td>
#item.ReimbursementId
</td>
<td>
#item.StaffName
</td>
<td>
#item.RequestDate
</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal" data-id="#item.RequerForApprovalId" data-target="#exampleModal" id="SelectBtn">Select</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="Title">Select and Confirm</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group" >
<input type="hidden" id="Reid" />
#Html.DropDownList("ApprovalStatus", null, new { #class = "btn btn-info",id="enumId" })
#*#Html.DropDownList("Index", ViewBag.DropDownList as SelectList,null, new { #class = "btn btn-info",#id="DropDownList" })*#
</div>
<hr />
<div class="form-group" style="visibility:visible" id="remarktext">
<label for="message-text" class="control-label">Remark:</label>
<textarea class="form-control" id="message-text" ></textarea>
</div>
</form>
</div>
<div class="modal-footer">
#*<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Confirme</button>*#
<button data-id="#item.ReimbursementId" class="btn btn-primary" id="Submit" #*onclick="location.href='#Url.Action("AddRequestForApproval","Reimbursements")'"*#>Submit</button>
<button class="btn btn-default" data-dismiss="modal" type="reset" id="Clear">Close</button>
</div>
</div>
</div>
</div>
</td>
</tr>
}
</table>
#section Scripts {
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#table1").on('click', '#SelectBtn', function () {
$('#Submit').click('#enumId', function () {
var bid = $(this).attr('data-id');
var status = $("#enumId option:selected").val();
var mess = $('#message-text').val();
var Rmid;
console.log(bid, status, mess);
// var b = $("#NewId");
#*if ($("#NewId").val() == undefined) {
Rmid = 0;
} else {
Rmid = $("#NewId").val();
}
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("saveStatus")',
data: { id: bid, status: status, Remark: mess },
success: function (data) {
console.log(data);
status.val('').url(data);
mess.val('');
}, error: function (data) {
alert("error");
},
})*#
})
})
})
</script>
}
Instead of putting data-id there, you can just put it as value of a hidden filed in your form so that it gets posted when the form submitted:
<input type = "hidden" name="id" value="#item.ReimbursementId" />
If the value may change that you want to send different values when different buttons are clicked, then you can have a hidden input and set its value before submit:
$('#Submit').click('#enumId', function () {
var bid = $(this).data('id');
$('[name="id"]').val(bid);
// rest of your code....
});
Edit: if you are going to post it with ajax, please note that you should get data like:
$(this).data('id');

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

Categories