Can't upload audio/video - c#

Here is my html part I want to choose and post a file to method in the server.
<div class="control-group">
<input type="hidden" name="id" data-bind="value: id" />
<div class="controls">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="fileupload-new thumbnail" style="width: 200px; height: 150px;">
<embed height="50" width="100" data-bind="attr: { src: mediaUrl() }" />
</div>
<div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;">
</div>
<div>
<span class="btn btn-file"><span class="fileupload-new">Choose a Audio/Voice</span> <span class="fileupload-exists">Change</span>
<input type="file" name="photoFile" class="default" />
</span><a data-bind="click: addMediaFile" href="#" class="btn fileupload-exists"
data-dismiss="fileupload">Save</a>
</div>
</div>
</div>
</div>
And here is addMediaFile javascript function in my ViewModel file
self.addMediaFile = function () {
utils.UIBlock();
$("#mediaForm").ajaxSubmit({
url: "api/Work/EditLibraryItemForMedia",
type: "POST",
success: function (result) {
self.mediaFilePath(result);
utils.UIUnBlock();
utils.showSuccess("Dosya kaydedilmiştir");
},
error: function () {
utils.UIUnBlock();
}
});
}
And finally here is my EditLibraryItemForMedia method in the server.
private Task<List<string>> UploadMediaFile()
{
string folderPath = ConfigurationManager.AppSettings["mediaFilesFolder"].ToString();
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(folderPath);
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
return Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(r => { return new List<string>(); });
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
string resizedImagesFolderPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Images/UploadedMedias/"));
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
return Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(
readTask =>
{
MultipartFormDataStreamProvider provider = readTask.Result;
return provider.FileData.Select(fileData =>
{
string itemId = provider.FormData["id"];
FileInfo fileInfo = new FileInfo(itemId);
string mimeType = GetMimeType(fileData.Headers.ContentDisposition.FileName);
string extension = "";
if (mimeType == "audio/mpeg3" || mimeType == "audio/x-mpeg-3" || mimeType == "video/mpeg" || mimeType == "video/x-mpeg")
{
extension = ".mp3";
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
// Add extensions to files
string fileName = itemId + extension;
string filePath = Path.Combine(folderPath, fileName);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.Move(fileData.LocalFileName, filePath);
WorkService.UpdateMediaFile(itemId, Path.GetFileName(filePath));
return fileName;
}).ToList();
});
}
Actually problem is that I can't upload an audio and video using this procedure.

Related

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

Trying to upload a file and display the files in a view

So I'm trying to build an virtual file storage, im stuck at the part where I have to upload files and after that display them in a File-s view so that the user can download, delete or see them. The form input together with the file upload is in a modal box. To process the modal form I have used #Html.BeginForm and to process the file upload I have used ajax. What I have achieved until now is that I can upload the files to the server folder, but I dont konw how I can save the file name and the file path to the database of file-s table. And I also need help on how to display these files in a specific view. Thank you in advance.
Html
<div class="modal-body">
#using (Html.BeginForm("SaveRecord", "NgarkoDokument", FormMethod.Post, new { enctype = "mulptiple/form-data" }))
{
<div class="form-group">
<label for="exampleFormControlSelect1">Lloji i dokumentit</label><br />
<select title="Lloji i dokumentit" name="lloji" class="form-control col-md-3 box" id="tipiDropdown"> </select>
<input type="button" title="Ngarko dokument" name="ngarko" value="Ngarko" id="uploadPop" class="btn btn-info col-md-3" onclick="document.getElementById('file').click();" />
<input type="file" onchange="javascript: updateList()" multiple="multiple" style="display:none;" id="file" name="postedFiles"/>
<div id="fileList"></div>
</div>
<br /><br />
<div class="form-group">
<label for="formGroupExampleInput">Fusha indeksimi</label> <br />
#*<input title="Indeksimi dokumentit" id="indeksimi" class="form-control col-md-3" type="text" name="indeksimi" placeholder="indeksimi" required />*#
#Html.TextBoxFor(a => a.Fusha_Indeksimit.Emri_Indeksimit, new { #class = "form-control", #placeholder = "indeksimi" })
#* <button title="Shto indeksim" id="modalPlus" type="submit" class="btn btn-info"><i class="glyphicon glyphicon-plus"></i></button>*#
</div>
<label for="formGroupExampleInput">Vendndodhja fizike e dokumentit</label><br>
<div id="zyraModal" class="form-group col-md-4">
#*<input title="Zyra fizike" id="zyra" class="form-control" type="text" name="zyra" placeholder="Zyra" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Zyra, new { #class = "form-control", #placeholder
= "Zyra" })
</div>
<div class="form-group col-md-4">
#* <input title="Kutia fizike" id="kutia" class="form-control" type="number" name="kutia" placeholder="Nr i kutisë" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Nr_Kutise, new { #class = "form-control", #placeholder = "Nr i kutisë" })
</div>
<div class="form-group col-md-4">
#* <input title="Rafti fizik" id="rafti" class="form-control" type="text" name="rafti" placeholder="Rafti" />*#
#Html.TextBoxFor(a => a.Vendndodhja_fizike.Rafti, new { #class = "form-control", #placeholder = "Rafti" })
</div>
<br /><br />
<div class="row" id="ruaj">
<button title="Ruaj dokumentin" type="submit" class="btn btn-success">Ruaj</button>
</div>
}
</div>
Ajax script
<script type="text/javascript">
$(document).ready(function () {
$("#file").change(function () {
console.log("Image selected!");
var formData = new FormData();
var totalFiles = document.getElementById("file").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("file").files[i];
formData.append("file", file);
}
$.ajax({
type: "POST",
url: '/UploadFile/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
}
});
});
});
</script>
Controller
public ActionResult Dokument()
{
return View();
}
[HttpPost]
public void Upload()
{
Dokumenti dok = new Dokumenti();
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/File/"), fileName);
file.SaveAs(path);
}
}
public ActionResult SaveRecord(NgarkoDokument model)
{
try
{
Vendndodhja_Fizike vendndodhja = new Vendndodhja_Fizike();
vendndodhja.Zyra = model.Vendndodhja_fizike.Zyra;
vendndodhja.Rafti = model.Vendndodhja_fizike.Rafti;
vendndodhja.Nr_Kutise = model.Vendndodhja_fizike.Nr_Kutise;
db.Vendndodhja_Fizike.Add(vendndodhja);
Fusha_Indeksimit indeksimi = new Fusha_Indeksimit();
indeksimi.Emri_Indeksimit = model.Fusha_Indeksimit.Emri_Indeksimit;
db.Fusha_Indeksimit.Add(indeksimi);
Dokumenti dok = new Dokumenti();
dok.Emer = model.Dokumenti.Emer;
db.Dokumenti.Add(dok);
db.SaveChanges();
//int lastUserId = dok.UserID;
}
catch(Exception ex)
{
throw ex;
}
return RedirectToAction("Dokument");
}
}
First of all, you may need to specify this because you send FormData to your controller. For example:
public async Task CreateAsync([FromForm] CreateBookDto input)
{
...
}
I care about a lot of things while uploading the file so my js file is a bit long but you can get what works for you:
$(function () {
var fileInput = document.getElementById('Book_CoverImageFile');
var file;
fileInput.addEventListener('change', function () {
var showModal = true;
file = fileInput.files[0];
document.getElementById("choose-cover-image").innerHTML = file.name;
var permittedExtensions = ["jpg", "jpeg", "png"]
var fileExtension = $(this).val().split('.').pop();
if (permittedExtensions.indexOf(fileExtension) === -1) {
showModal = false;
alert('This extension is not allowed')
$('#Book_CoverImageFile').val('');
$("#choose-cover-image").html("Choose a cover image...");
}
else if(file.size > 5*1024*1024) {
showModal = false;
alert('The file is too large');
}
var img = new Image();
img.onload = function() {
var sizes = {
width:this.width,
height: this.height
};
URL.revokeObjectURL(this.src);
if (sizes.width > 1920 && sizes.height > 1080){
alert('Height and Width must not exceed 1920*1080.')
$('#Book_CoverImageFile').val('');
$("#choose-cover-image").html("Choose a cover image...");
}
var aspectRatio = sizes.width / sizes.height;
aspectRatio = Number (aspectRatio.toFixed(1));
if (aspectRatio !== 1.8){
alert("The picture you uploaded is not in 16:9 aspect ratio!")
$('#Book_CoverImageFile').val('');
$("#choose-cover-image").html("Choose a cover image...");
}
}
if(showModal === true) {
readURL(this);
$('#myModal').modal('show');
}
var objectURL = URL.createObjectURL(file);
img.src = objectURL;
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img-upload').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$('form#CreateBookForm').submit(function (e) {
e.preventDefault();
var title = $('#Book_Title').val().trim();
var formData = new FormData();
formData.append("Title", title);
formData.append("CoverImageFile", file);
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
if(percentComplete !== 100){
$( '#Book_CoverImageFile' ).prop( "disabled", true );
$( '#Book_Title' ).prop( "disabled", true );
$( '#btnSubmit' ).prop( "disabled", true );
}
}
}, false);
return xhr;
},
url: app.appPath + `api/app/Book`,
data: formData,
type: 'POST',
contentType: false,
processData: false,
success: function(data){
alert("The Book has been successfully submitted. It will be published after a review from the site admin.");
window.location.href = "/books";
},
error: function (data) {
alert(data.responseJSON.error.message);
}
});
});
This does many things, for example; file permitted extension control, control of file size, checking whether the file is more than 1920 * 1080 pixels, whether the file has 16:9 aspect ratio, disabling form elements while sending the file, etc...
And if you really care about security, you should;
To only accept permitted extensions:
public class AllowedExtensionsAttribute : ValidationAttribute
{
private readonly string[] _extensions;
public AllowedExtensionsAttribute(string[] extensions)
{
_extensions = extensions;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
if (value == null) // If uploading a file is optional on the form screen, it should be added == CanBeNul
{
return ValidationResult.Success;
}
var file = value as IFormFile;
var extension = Path.GetExtension(file.FileName);
if (file.Length > 0 && file != null)
{
if (!_extensions.Contains(extension.ToLower()))
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"This extension is not allowed!";
}
}
To limit the uploaded file size:
public class MaxFileSizeAttribute : ValidationAttribute
{
private readonly int _maxFileSize;
public MaxFileSizeAttribute(int maxFileSize)
{
_maxFileSize = maxFileSize;
}
protected override ValidationResult IsValid(
object value, ValidationContext validationContext)
{
if (value == null) // If uploading a file is optional on the form screen, it should be added == CanBeNull
{
return ValidationResult.Success;
}
var file = value as IFormFile;
if (file.Length > 0)
{
if (file.Length > _maxFileSize)
{
return new ValidationResult(GetErrorMessage());
}
}
return ValidationResult.Success;
}
public string GetErrorMessage()
{
return $"Maximum allowed file size is { _maxFileSize} bytes.";
}
}
And you must add them to Dto:
public class CreateBookDto
{
[Required]
[StringLength(64)]
public string Title { get; set; }
[CanBeNull]
[DataType(DataType.Upload)]
[MaxFileSize(5*1024*1024)] // 5mb
[AllowedExtensions(new string[] { ".jpg", ".png", ".jpeg" })]
public IFormFile CoverImageFile { get; set; }
}
Finally, your HTML file should look like this:
<form method="post" id="CreateBookForm" asp-page="/Book/Create" enctype="multipart/form-data">
<div class="form-group">
<div class="custom-file">
<input asp-for="Book.CoverImageFile" type="file" name="file" class="custom-file-input" id="Book_CoverImageFile"
required="required">
<label id="choose-cover-image" class="custom-file-label" for="customFile">Choose a cover image...</label>
<small class="form-text text-muted">#L["CreateBookCoverInfo"].Value</small>
</div>
</div>
...
<button id="btnSubmit" type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<img class="img-fluid" id="img-upload" alt=""/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-block" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

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

How to fix Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference in asp.net mvc?

I get the following exception in my system.This system worked properly. But suddenly got and exception. I tried doing debugging. But I couldn't find the anything. This is about a profile picture upload. I did some removing of code and I got the error. But then I again add those codes but nothing happen. I tried some solutions in the internet but didn't work. I'm new to this work so please help me if you can. I tried removing some of the codes then I got an error saying invalid operation.
How can I fix this?
I tried to debug and find where the problem occurs, unfortunately I couldn't find where it is.But I guess the problem should be in these codes. These two codes created the exception
Code part 1
#{
var imgUrl = #Url.Content("~/Content/profile/" + Model.SID + ".png") + "?time=" + DateTime.Now.ToString();
}
<img id="user_img" src="#imgUrl" height="50" width="50" style="margin-top:2px" />
</li>
Code part 2
#if (Model.SID != null)
{
var imgUrl = #Url.Content("Content/profile/" + Model.SID + ".png") + "?time=" + DateTime.Now.ToString();
<div class="input-field col s12">
<div class="input-field col s12">
<img id="user_img" src="#imgUrl" height="1" width="1" />
</div>
<div class="mngimg">
#using (Html.BeginForm("UploadPhoto", "Profile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="input-field col s12">
<input type="file" name="file" id="files" onchange="this.form.submit()" />
</div>
}
</div>
</div>
}
#section Scripts
{
<script>
$(document).ready(function () {
$.validator.setDefaults({
errorClass: 'invalid',
validClass: "valid",
errorPlacement: function (error, element) {
$(element)
.closest("form")
.find("label[for='" + element.attr("id") + "']")
.attr('data-error', error.text());
},
submitHandler: function () {
event.preventDefault();
var SID = $("[name='SID']").val();
var fName = $("[name='fname']").val();
var lName = $("[name='lname']").val();
var dob = $("[name='dob']").val();
var email = $("[name='email']").val();
var pw = $("[name='password']").val();
var confirmPw = $("[name='confirmPassword']").val();
var phone = $("[name='phone']").val();
var address = $("[name='address']").val();
var user = {
SID: SID,
FirstName: fName,
LastName: lName,
DOB: dob,
email: email,
Password: password,
Phone: phone,
Address: address
}
//console.log(SID + " " + email + " " + password);
$.ajax({
type: 'POST',
url: 'saveChanges',
contentType: 'application/json',
data: JSON.stringify(user),
dataType: 'Json',
async: true,
success: function (data) {
if (data == true) {
Materialize.toast('Details Updated Successfully !!!', 4000, 'blue')
}
}
});
}
});
$.validator.addMethod("regx", function (value, element, regexpr) {
return regexpr.test(value);
}, "must contain more than 8 characters & at least 1 Alphabet and 1 Number");
$("#form").validate({
rules: {
SID: {
required: true,
minlength: 10,
maxlength: 10
},
fName: {
required: true,
minlength: 4,
maxlength: 20
},
lName: {
required: true,
minlength: 4,
maxlength: 20
},
dob: {
required: true,
},
email: {
required: true,
email: true
},
Phone: {
required: true,
regx: /^\d{10}$/,
minlength: 10,
maxlength: 10
},
},
messages: {
fName: {
required: true,
minlength: "Should be minimum 4 characters",
maxlength: "Should be maximum 20 characters",
},
lName: {
required: true,
minlength: "Should be minimum 4 characters",
maxlength: "Should be maximum 20 characters"
},
Phone: {
minlength: "Enter valid phone number",
maxlength: "Enter valid phone number"
}
}
});
});
</script>
}
<form id="form" style="width:100%; height:auto; margin-left:1%; margin-top:1%" method="post">
#*<div class="input-field col s12 ">
<i class="material-icons prefix">account_circle</i>
<input id="img" name="img" type="image" value="" readonly="readonly" style="margin-top:5%; margin-bottom:1%">
<label for="img">Profile Picture</label>
</div>*#
<div class="input-field col s12 ">
<i class="material-icons prefix">subtitles</i>
<input id="SID" name="SID" type="text" value="#Model.SID" readonly="readonly">
<label for="SID">Student ID</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input id="fname" name="fname" type="text" class="validate" value="#Model.FirstName">
<label for="fname">First Name</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input id="lname" name="lname" type="text" class="validate" value="#Model.LastName">
<label for="lname">Last Name</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">Address</i>
<input id="address" name="address" type="text" class="validate" value="#Model.Address">
<label for="lname">Address</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">phone</i>
<input id="phone" name="phone" type="text" class="validate" value="#Model.Phone">
<label for="lname">Phone</label>
</div>
<label for="dob" style="margin-left:10%">Date of Birth</label>
<div class="input-field col s12">
<i class="material-icons prefix">D</i>
<input id="dob" name="dob" type="date" class="validate" value="#Model.DOB.Value.ToString("dd/ MM/ yyyy")"> #*#Model.DOB.Value.ToString("mm/dd/yyyy")*#
</div>
<div class="input-field col s12">
<i class="material-icons prefix">email</i>
<input id="email" name="email" type="email" class="validate" value="#Model.email">
<label for="email">Email</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">lock_outline</i>
<input id="password" name="password" type="password" class="validate">
<label for="password">Password</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">lock_outline</i>
<input id="confirmPassword" name="confirmPassword" type="password" class="validate" onkeyup="check()">
<label for="confirmPassword">Confirm Password</label>
<lable name="checkpassword"></lable>
</div>
<div class="input-field col s12">
<input class="btn waves-effect waves-light" id="submit" type="submit" name="action" style="width:33%; margin-left:20%; margin-bottom:4%">
</div>
#*</div>*#
</form>
Controller
public ActionResult Index()
{
Session["userID"] = "IT14111884";
string sessionValue = Session["userID"].ToString();
if (Session["userID"].ToString() == null) return View("Login");
person1 = repo.GetPeronById(sessionValue);
var model = person1;
//DateTime da = (DateTime)person1.DOB;
//DateTime date2 = ;
//DateTime.ToString("dd MMM yyyy")
return View(model);
}
[HttpPost]
public JsonResult saveChanges(person person1)
{
person _person = new person();
_person.SID = person1.SID;
_person.FirstName = person1.FirstName;
_person.LastName = person1.LastName;
_person.Address = person1.Address;
_person.Phone = person1.Phone;
_person.DOB = person1.DOB;
_person.password = person1.password;
_person.email = person1.email;
//Session["_person"] = _person;
string sessionValue = Session["userID"].ToString();
bool status;
if (!ModelState.IsValid) return Json(false, JsonRequestBehavior.AllowGet);
status = repo.updatePerson(sessionValue,_person);
return Json(status, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult UploadPhoto(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var user = Session["userID"].ToString();
var fileExt = Path.GetExtension(file.FileName);
if (fileExt.ToLower().EndsWith(".png") || fileExt.ToLower().EndsWith(".jpg"))
{
var fileName = user + ".png";
var filePath = HostingEnvironment.MapPath("~/Content/profile/") + fileName;
var directory = new DirectoryInfo(HostingEnvironment.MapPath("~/Content/profile/"));
if (directory.Exists == false)
{
directory.Create();
}
ViewBag.FilePath = filePath.ToString();
file.SaveAs(filePath);
return RedirectToAction("Index", new { Message = ManageMessageId.PhotoUploadSuccess });
}
else
{
return RedirectToAction("Index", new { Message = ManageMessageId.FileExtensionError });
}
}
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
public enum ManageMessageId
{
Error,
PhotoUploadSuccess,
FileExtensionError
}
Reporsitory class
public bool updatePerson(string ID,person _objPerson)
{
//_dbContext.people.Add(_objPerson);
person temp = null;
try
{
temp = (from p in _dbContext.people
where p.SID == ID
select p).SingleOrDefault();
temp.FirstName = _objPerson.FirstName;
temp.LastName = _objPerson.LastName;
temp.Address = _objPerson.Address;
temp.Phone = _objPerson.Phone;
temp.DOB = _objPerson.DOB;
temp.password = _objPerson.password;
temp.email = _objPerson.email;
//_dbContext.SaveChanges();
//Guid id = _objPerson.Person_ID;
if (_dbContext.SaveChanges() > 0)
{
return true;
}
}
catch (DbUpdateException e)
{
string msg = (e.InnerException.Message);
//Console.ReadLine();
}
return false;
}

mvc ajax form post null list issue

Here is my ajax form of my view:
#using (Ajax.BeginForm("SendIndoorRequest", "TestRequest", new AjaxOptions { OnBegin = "SendRequestBegin", OnComplete = "SendRequestComplete", OnFailure = "SendRequestFail", OnSuccess = "SendRequestSuccess" }, new { enctype = "multipart/form-data", id = "ImgUpload" }))
{
<input type="hidden" name="CliqPanelID" value="#ViewBag.OrgID" />
<input type="hidden" name="TypeOfRequest" value="I" />
<input type="hidden" name="patient_id" value="#ViewBag.PatientId" />
<input type="hidden" name="bed_no" value="#ViewBag.PatientBedNo" />
<input type="hidden" name="ward_no" value="#ViewBag.PatientWardNo" />
#*<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>*#
<div class="row" style="margin-top:5px;margin-bottom:5px;">
#*input fields*#
<div class="col-lg-8">
<div class="col-lg-4">
<div class="col-lg-12"><label>Request Type:</label></div>
<div class="col-lg-12">
#Html.DropDownList("RequestType", null, "Select Request Type", new { #style = "width:170px;", #id = "ddlRequestType" })
</div>
<div id="ddlRequestTypeValidate" style="margin-left:12px;color:red;display:none;">
Select Request Type
</div>
</div>
<div class="col-lg-4">
<div class="col-lg-12"><label>Reffering Doctor:</label></div>
<div class="col-lg-12">
#Html.DropDownList("CliqDoctorID", null, "Select Reffering Doctor", new { #style = "width:180px;", id = "ddlRefDoctors", #class = "chosen-select" })
</div>
<div id="ddlRefDoctorsValidate" style="margin-left:12px;color:red;display:none;">
Select Reffering Doctor
</div>
</div>
<div class="col-lg-4">
<div class="col-lg-12"><label>Doctor Name</label>
</div>
<div class="col-lg-12">
#Html.TextBoxFor(o => o.DoctorName, new { placeholder = "In case Doctor not in list" })
</div>
<div id="DoctorNameValidate" style="margin-left:12px;color:red;display:none;">
Enter Reffering Doctor
</div>
</div>
#Html.HiddenFor(o => o.BookedTestsIds, new { #id = "bookedTestsIds" })
#*#Html.HiddenFor(o => o.)*#
#*<input type="hidden" name="Tests[0].TestId" value="1" />
<input type="hidden" name="Tests[0].Charges" value="100" />*#
<div style"clear:both; margin-bottom:5px;"></div>
<div class="col-lg-4">
<div class="col-lg-12"><label>Authorization Code:</label></div>
<div class="col-lg-12">
#if (Session["AccountType"].ToString() == "panel")
{
#Html.TextBoxFor(o => o.AuthCode1, new { #disabled = "disabled" })
#Html.HiddenFor(o => o.AuthCode1)
}
else
{
#Html.TextBoxFor(o => o.AuthCode1)
}
</div>
<div id="AuthCode1Validate" style="margin-left:12px;color:red;display:none;">
Enter Authorization Code
</div>
</div>
#*<div class="col-lg-4">
<div class="col-lg-12"><label>Prescription Reference:</label></div>
<div class="col-lg-12">
<input type="file" id="uploadFile" name="files"><br>
<span id="uploadLoader" style="display:none;"><img id="searchLoader" src="#Url.Content("~/Images/loader.gif")" />Uploading Please Wait</span>
</div>
<div style="margin-left:12px;color:red;">
</div>
</div>*#
<div class="col-lg-4">
<div class="col-lg-12"><label>Prescription Reference:</label></div>
<div class="col-lg-12">
<div id="uploadControlContainer">
<input type="file" name="fileUpload" value="" id="uploadFile" />
<p>Upload Files</p>
</div>
</div>
<input type="hidden" name="FilePath" value="" id="UploadedFile" />
<div style="margin-left:12px;color:red;">
</div>
</div>
<div class="col-lg-3">
<div class="col-lg-12">
</div>
<div class="col-lg-12">
<input class="btn btn-primary" style="padding: 0 5px; !important;" id="btnSendRequest" type="submit" value="Send Request"/>
</div>
</div>
</div>
#*input fields portion end*#
#*card portion*#
<div class="col-lg-4" style="background:white; border-radius:4px;padding:4px; box-shadow: 2px 2px 2px 2px #888888; width:32.333% !important; margin-left:10px;">
<div class="col-lg-2" style="padding-left: 4px !important;padding-right: 2px; !important"><img id="PatientPic" src="" style=" width: 100%;" /></div>
<div class="col-lg-10" style="padding-left: 4px !important;padding-right: 2px; !important">
<div class="col-lg-3" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:11px; color:#428BCA;"><strong>Patient:</strong></div>
<div class="col-lg-9" id="EmpName" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:12px;">#ViewBag.PatientName </div>
<div style="clear:both;"></div>
<div class="col-lg-3" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:11px; color:#428BCA;"><strong>Ward/Room:</strong></div>
<div class="col-lg-9" id="DepName" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:12px;">#ViewBag.PatientWardNo </div>
<div style="clear:both;"></div>
<div class="col-lg-3" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:11px; color:#428BCA;"><strong>Bed No:</strong></div>
<div class="col-lg-9" id="Relation" style="padding-left: 4px !important;padding-right: 2px; !important; font-size:12px;">#ViewBag.PatientBedNo </div>
</div>
</div>
#*card portion end*#
</div>
<div id="panelTestsContainer">
</div>
<div id="hiddenContainer">
<input type="hidden" id="delimCharges" />
<input type="hidden" id="delimTestId" />
<input type="hidden" id="delimTestName" />
</div>
<div id="BookedTestsContainer">
</div>
}
on my view there are checkboxes with test name on check box checked or unchecked event i sent an ajax call to maintain list on server side but if i only i check 1 test the list posted is null but when i check more than 1 then list is posted with right count and data, whats the issue i am not getting:
Here is my jquery code for checkbox event:
$("input.checkBoxTests").live('change', function () {
var TestID = this.id;
var charges = $('#sample-table-3').find('td.TestCharges#' + TestID).html();
var TestName = $('#sample-table-3').find('td.TestName#' + TestID).html()
if (this.checked) {
var AddUrl = '#Url.Action("AddTest","TestRequest")';
$.post(AddUrl,
{ TestId: TestID, Charges: charges, TestName: TestName },
function (response) {
$("div#BookedTestsContainer").html(response);
});
$("#selectedTestsTable").find('tbody')
.append($('<tr>')
.attr('id', TestID)
.attr('class', "bookedTest")
.append($('<td>')
.append($('#sample-table-3').find('td.TestName#' + TestID).html()
)
)
);
}
else {
var RemoveUrl = '#Url.Action("RemoveTest","TestRequest")';
$.post(RemoveUrl,
{ TestId: TestID, Charges: charges, TestName: TestName },
function (response) {
$("div#BookedTestsContainer").html(response);
});
$("#selectedTestsTable").find('tr#' + TestID).remove()
}
});
here is my ajax call server event when checkbox is checked:
[HttpPost]
public ActionResult AddTest(int TestId,long Charges, string TestName)
{
List<Test> bookedTests = new List<Test>();
if (Session["BookedTests"] != null)
{
bookedTests = (List<Test>)Session["BookedTests"];
}
Test objTest = new Test();
objTest.TestId = TestId;
objTest.Charges = Charges;
objTest.TestName = TestName;
bookedTests.Add(objTest);
Session["BookedTests"] = bookedTests;
return PartialView("~/Views/TestRequest/_HiddenTestsPartial.cshtml",bookedTests);
}
here is my ajax call server side event when checkbox is unchecked:
[HttpPost]
public ActionResult RemoveTest(int TestId)
{
List<Test> bookedTests = new List<Test>();
if (Session["BookedTests"] != null)
{
bookedTests = (List<Test>)Session["BookedTests"];
bookedTests.RemoveAll(key => key.TestId == TestId);
Session["BookedTests"] = bookedTests;
return PartialView("~/Views/TestRequest/_HiddenTestsPartial.cshtml", bookedTests);
}
else
{
return new EmptyResult();
}
}
Here is my form post method:
[HttpPost]
public string SendIndoorRequest(TestRequestViewModel form, IEnumerable<HttpPostedFileBase> files)
{
using (var db = new cloud_clinicEntities())
using (var scope = new TransactionScope())
{
org_requestm objRequestM = new org_requestm();
objRequestM.authcode1 = form.AuthCode1;
objRequestM.admission_no = form.admission_no;
objRequestM.bed_no = form.bed_no;
objRequestM.ward_no = form.ward_no;
objRequestM.patient_id = form.patient_id;
objRequestM.RequestType = form.TypeOfRequest;
if (form.DependentId == 0)
{
objRequestM.cliq_dependent_id = null;
}
else
{
objRequestM.cliq_dependent_id = form.DependentId;
}
if (form.CliqDoctorID != 0)
{
objRequestM.cliq_doctor_id = form.CliqDoctorID;
}
if (!string.IsNullOrEmpty(form.DoctorName))
{
objRequestM.doctor_name = form.DoctorName;
}
objRequestM.request_total_amount = 0;
for (int i = 0; i < form.BookedTests.Count; i++)
{
if (form.BookedTests[i].Charges != 0)
{
objRequestM.request_total_amount = objRequestM.request_total_amount + form.BookedTests[i].Charges;
}
}
objRequestM.cliq_panel_id = form.CliqPanelID;
if (Session["AccountType"].ToString() == "lab")
{
objRequestM.enteredby_clinicPersonId = int.Parse(Session["userId"].ToString());
}
else
{
objRequestM.enteredby_orgPersonId = int.Parse(Session["userId"].ToString());
}
objRequestM.enteredon = DateTime.Now;
objRequestM.org_request_type_id = form.RequestType;
if (Request.Files != null)
{
foreach (string requestFile in Request.Files)
{
HttpPostedFileBase file = Request.Files[requestFile];
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string directory = Server.MapPath("~/uploads/");
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string path = Path.Combine(directory, fileName);
file.SaveAs(path);
objRequestM.perscription_doc_path = "~/Uploads/" + file.FileName;
}
}
}
db.org_requestm.Add(objRequestM);
db.SaveChanges();
long RequestmId = db.org_requestm.Max(o => o.id);
for (int i = 0; i < form.BookedTests.Count; i++)
{
if (form.BookedTests[i].TestId != 0)
{
org_requestd objRequestd = new org_requestd();
objRequestd.amount = form.BookedTests[i].Charges;
objRequestd.lims_test_id = form.BookedTests[i].TestId;
objRequestd.lims_test_name = form.BookedTests[i].TestName;
objRequestd.Status = "P";
objRequestd.requestm_id = RequestmId;
db.org_requestd.Add(objRequestd);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
var outputLines = new List<string>();
foreach (var eve in e.EntityValidationErrors)
{
outputLines.Add(string.Format(
"{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
outputLines.Add(string.Format(
"- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage));
}
}
System.IO.File.AppendAllLines(#"d:\EFerrors.txt", outputLines);
}
}
}
scope.Complete();
Session.Remove("BookedTests");
return "success";
}
}
here is my checkbox event:
$("input.checkBoxTests").live('change', function () {
var TestID = this.id;
var charges = $('#sample-table-3').find('td.TestCharges#' + TestID).html();
var TestName = $('#sample-table-3').find('td.TestName#' + TestID).html()
if (this.checked) {
var AddUrl = '#Url.Action("AddTest","TestRequest")';
//AddUrl = AddUrl + "?TestId=" + TestID + "&Charges=" + charges + "&TestName=" + TestName;
$.post(AddUrl,
{ TestId: TestID, Charges: charges, TestName: TestName },
function (response) {
$("div#BookedTestsContainer").html(response);
});
$("#selectedTestsTable").find('tbody')
.append($('<tr>')
.attr('id', TestID)
.attr('class', "bookedTest")
.append($('<td>')
.append($('#sample-table-3').find('td.TestName#' + TestID).html()
)
)
);
/*var TestIdIndex = $("input.iHiddenTestId").length;
var Mytest = $('input.MyTest').length;
alert('my' + Mytest);
$('form#ImgUpload input.iHiddenTestId').each(function (i) {
// do something
alert($(this).val());
});
var newTestId = $("<input id='" + this.id + "' type='hidden' value='" + this.id + "' class='iHiddenTestId' name='Tests[" + TestIdIndex + "].TestId' />");
$("form#ImgUpload").append(newTestId);
var Testing = $("<input id='" + this.id + "' type='hidden' value='" + this.id + "' class='MyTest' name='Tests[" + TestIdIndex + "].TestId' />");
$("form#ImgUpload").append(Testing);
var ChargesIndex = $("form#ImgUpload input.iHiddenCharges").length;
var newCharges = $("<input id='" + this.id + "' type='hidden' value='" + charges + "' class='iHiddenCharges' name='Tests[" + ChargesIndex + "].Charges' />");
$("form#ImgUpload").append(newCharges);
var TestNameIndex = $("form#ImgUpload input.iHiddenTestName").length;
var newTestName = $("<input id='" + this.id + "' type='hidden' value='" + TestName + "' class='iHiddenTestName' name='Tests[" + TestNameIndex + "].TestName' />");
$("form#ImgUpload").append(newTestName);*/
}
else {
var RemoveUrl = '#Url.Action("RemoveTest","TestRequest")';
$.post(RemoveUrl,
{ TestId: TestID, Charges: charges, TestName: TestName },
function (response) {
$("div#BookedTestsContainer").html(response);
});
$("#selectedTestsTable").find('tr#' + TestID).remove()
}
});
What i did after messing up with it that on list creating on Add Test i added a dummy empty entry on index 0 of the list and on retrieving while saving in db i am skipping the 0th index of the list, here is the code:
[HttpPost]
public ActionResult AddTest(int TestId,long Charges, string TestName)
{
List<Test> bookedTests = new List<Test>();
if (Session["BookedTests"] != null)
{
bookedTests = (List<Test>)Session["BookedTests"];
}
else
{
Test dummyTest = new Test();
dummyTest.TestId = 0;
dummyTest.Charges = 0;
dummyTest.TestName = "dummy";
bookedTests.Add(dummyTest);
}
Test objTest = new Test();
objTest.TestId = TestId;
objTest.Charges = Charges;
objTest.TestName = TestName;
bookedTests.Add(objTest);
Session["BookedTests"] = bookedTests;
return PartialView("~/Views/TestRequest/_HiddenTestsPartial.cshtml",bookedTests);
}
and here is the Saving in which i am skipping the first item of list:
[HttpPost]
public string SendIndoorRequest(TestRequestViewModel form, IEnumerable<HttpPostedFileBase> files)
{
using (var db = new cloud_clinicEntities())
using (var scope = new TransactionScope())
{
org_requestm objRequestM = new org_requestm();
objRequestM.authcode1 = form.AuthCode1;
objRequestM.admission_no = form.admission_no;
objRequestM.bed_no = form.bed_no;
objRequestM.ward_no = form.ward_no;
objRequestM.patient_id = form.patient_id;
objRequestM.RequestType = form.TypeOfRequest;
if (form.DependentId == 0)
{
objRequestM.cliq_dependent_id = null;
}
else
{
objRequestM.cliq_dependent_id = form.DependentId;
}
if (form.CliqDoctorID != 0)
{
objRequestM.cliq_doctor_id = form.CliqDoctorID;
}
if (!string.IsNullOrEmpty(form.DoctorName))
{
objRequestM.doctor_name = form.DoctorName;
}
objRequestM.request_total_amount = 0;
for (int i = 0; i < form.BookedTests.Count; i++)
{
if (form.BookedTests[i].Charges != 0)
{
objRequestM.request_total_amount = objRequestM.request_total_amount + form.BookedTests[i].Charges;
}
}
objRequestM.cliq_panel_id = form.CliqPanelID;
if (Session["AccountType"].ToString() == "lab")
{
objRequestM.enteredby_clinicPersonId = int.Parse(Session["userId"].ToString());
}
else
{
objRequestM.enteredby_orgPersonId = int.Parse(Session["userId"].ToString());
}
objRequestM.enteredon = DateTime.Now;
objRequestM.org_request_type_id = form.RequestType;
if (Request.Files != null)
{
foreach (string requestFile in Request.Files)
{
HttpPostedFileBase file = Request.Files[requestFile];
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string directory = Server.MapPath("~/uploads/");
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string path = Path.Combine(directory, fileName);
file.SaveAs(path);
objRequestM.perscription_doc_path = "~/Uploads/" + file.FileName;
}
}
}
db.org_requestm.Add(objRequestM);
db.SaveChanges();
long RequestmId = db.org_requestm.Max(o => o.id);
for (int i = 0; i < form.BookedTests.Count; i++)
{
if (form.BookedTests[i].TestId != 0)
{
org_requestd objRequestd = new org_requestd();
objRequestd.amount = form.BookedTests[i].Charges;
objRequestd.lims_test_id = form.BookedTests[i].TestId;
objRequestd.lims_test_name = form.BookedTests[i].TestName;
objRequestd.Status = "P";
objRequestd.requestm_id = RequestmId;
db.org_requestd.Add(objRequestd);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
var outputLines = new List<string>();
foreach (var eve in e.EntityValidationErrors)
{
outputLines.Add(string.Format(
"{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
outputLines.Add(string.Format(
"- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage));
}
}
System.IO.File.AppendAllLines(#"d:\EFerrors.txt", outputLines);
}
}
}
scope.Complete();
Session.Remove("BookedTests");
return "success";
}
}

Categories