Problem with my Jquery function dosent call controllerside method - c#

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 ....

Related

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 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);
}

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

I am having trouble binding knockout js viewmodel

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?

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;
}

Categories