public ActionResult UploadImage(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
try
{
string path = Path.Combine(Server.MapPath("~/Images"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.FileStatus = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.FileStatus = "ERROR:" + ex.Message.ToString();
}
}
else
{
ViewBag.FileStatus = "You have not specified a file.";
}
return Json("No files selected.", JsonRequestBehavior.AllowGet);
}
Second ActionResult PhysicianBiodata()
public ActionResult PhysicianBiodata (int? Id)
{
PhysicianBiodata newForm = new PhysicianBiodata();
if (Id <= 0 || Id == null)
{
return RedirectToAction("UploadImage", "ServiceCompendium",
{HttpPostedFileBase httpPostedFileBase});
}
else
{
newForm = compendiumData.GetPhysicianBiodatas().Where(x => x.ID == Id)
.FirstOrDefault();
}
return View(newForm);
}
and I want to call this UploadImage() into PhysicianBiodata() but its not working. Can you please help me....
Can you fix the last argument to the redirect?
Something like
return RedirectToAction("UploadImage", "ServiceCompendium", { new #file =httpPostedFileBase});
Also, where is httpPostedFileBase in the PhysicianBiodata method?
Related
[HttpPost]
public async Task<IActionResult> UploadImage(ImageViewModel imageviewmodel, IFormFile Image)
{
var user = new AdminController(_context).GetUserId(Request);
if (user != null)
{
imageViewModel.Id = user.Id;
string name = $"{DateTime.UtcNow.Ticks}-";
if (Image == null || Image.Length == 0)
return Content("File not found");
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot/Images", Image.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await Image.CopyToAsync(stream);
string content_type = Image.ContentType;
}
imageviewmodel.Image = name + Image.FileName;
_context.ImageViewModels.Update(imageviewmodel);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
else
{
return Redirect("/Account/Login");
}
}
I am writing an application that imports from excel and save in database using asp.net mvc and wcf
Controller
[HttpPost]
public JsonResult UploadExcel(FIRS firs, 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 = Server.MapPath("~/FileUpload/");
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 [Sheet1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "ExcelTable");
DataTable dtable = ds.Tables["ExcelTable"];
string sheetName = "Sheet1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var firsRecords = from a in excelFile.Worksheet<FIRS>(sheetName) select a;
foreach (var a in firsRecords)
{
try
{
if (a.RC_NUMBER != "" && a.TIN_NUMBER != "" && a.COMPANY_NAME != "" && a.TCC_NUMBER != "")
{
FIRS TU = new FIRS();
var helper = new FirsServiceClient();
TU.RC_NUMBER = a.RC_NUMBER;
TU.TIN_NUMBER = a.TIN_NUMBER;
TU.COMPANY_NAME = a.COMPANY_NAME;
TU.TCC_NUMBER = a.TCC_NUMBER;
//db.FIRS.Add(TU);
//_firsService.AddFirs(TU);
//svc.SaveFirsImportData(TU);
//helper.SaveFirsImportData(TU);
TU.ACTION_STATUS = 1;
TU.CREATED_DATE = DateTime.Now;
_firsService.AddFirs(firs);
}
else
{
data.Add("<ul>");
if (a.RC_NUMBER == "" || a.RC_NUMBER == null) data.Add("<li> RC Number is required</li>");
if (a.TIN_NUMBER == "" || a.TIN_NUMBER == null) data.Add("<li>RC Number is required</li>");
if (a.COMPANY_NAME == "" || a.COMPANY_NAME == null) data.Add("<li>Company Name is required</li>");
if (a.TCC_NUMBER == "" || a.TCC_NUMBER == null) data.Add("<li> TCC Number is required</li>");
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);
}
return Json("success", JsonRequestBehavior.AllowGet);
}
else
{
//alert message for invalid file format
data.Add("<ul>");
data.Add("<li>Only Excel file format is allowed</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
else
{
data.Add("<ul>");
if (FileUpload == null) data.Add("<li>Please choose Excel file</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
Service.svc
public void AddFirs(FIRS firs)
{
_firsManager.AddFirs(firs);
}
When upload excel is click from view, it calls the controller public JsonResult UploadExcel(FIRS firs, HttpPostedFileBase FileUpload) Then, the controller reference the service AddFirs(FIRS firs) to save data to the database.
Why am I getting this error, and how can I resolve it.
Then, when I tried to debug by trapping the error I got this.:
I then used quickwatch. It tells me Some fields (PropertyName) like RC_NUMBER, tin_number, TCC_NUMBER are required.
I checked those fields in Excel that I tried to import, they are not empty. Please what do I do?
On login I am just assigning values to session but after login it becomes null. I set the session timeout as well but still it doesn't work.
public ActionResult Login([Bind(Include = "Username, Password")] LoginModel loginModel, string ReturnUrl)
{
if (ModelState.IsValid)
{
Egov_Users eGov_Users = db.Egov_Users
.Where(p => p.UserType.Type != "O" && p.UserName == loginModel.Username)
.FirstOrDefault();
if (eGov_Users == null)
{
ModelState.AddModelError("", "Invalid username");
return View();
}
else
{
if (eGov_Users.Password != loginModel.Password)
{
ModelState.AddModelError("", "Invalid Password");
return View();
}
var loginDetail = new LoginDetails();
loginDetail.supplierID = (eGov_Users.SupplierID != null) ? eGov_Users.SupplierID.Value : 0;
loginDetail.userID = eGov_Users.UserId;
loginDetail.username = eGov_Users.UserName;
loginDetail.firstName = eGov_Users.FirstName;
loginDetail.lastName = eGov_Users.LastName;
Session["UserID"] = loginDetail.userID;
Session["SupplierID"] = loginDetail.supplierID;
Session["Username"] = loginDetail.username;
Session["DisplayName"] = loginDetail.firstName + " " + loginDetail.lastName;
if (string.IsNullOrEmpty(ReturnUrl))
{
return RedirectToAction("Index", "Users");
}
}
}
return RedirectToAction("Login", "Login");
}
In webconfig I have set the session timeout as well.
Here i'm using Repo Class in that i wrote some Logic.When that Logic success I want to pass that string msg to mvc controller please Help me
Repo.cs
public void validateUser(Auth aut)
{
var xx=aut.Email;
var xr=db.Auths.Where(rr=>rr.Email == xx).FirstOrDefault();
if (xr != null)
{
var x = (from n in db.Auths
where n.Email == xr.Email && n.Password == xr.Password
select n).FirstOrDefault();
if (x != null)
{
var xz = (from n in db.Auths
where n.Email == xr.Email && n.Password == xr.Password && n.Active == aut.Active
select n).FirstOrDefault();
if (xz != null)
{
string Acc = "Your Account Activated....";
}
}
}
else
{string ddd = "Your Account not Activated....";}}
Controller.cs
Repo objrepo = new Repo();
public ActionResult Login(Auth aut)
{
if (ModelState.IsValid)
{
objrepo.validateUser(aut);
ViewBag.Success = "Success.....";
}
else
ViewBag.msg = "Invalid.....";
return View();
}
You could try this:
public string validateUser(Auth aut)
{
string result = "Invalid Email Address ....";
var xx=aut.Email;
var xr=db.Auths.Where(rr=>rr.Email == xx).FirstOrDefault();
if (xr != null)
{
result = "Invalid Password ....";
var x = (from n in db.Auths
where n.Email == xr.Email && n.Password == xr.Password
select n).FirstOrDefault();
if (x != null)
{
result = "Your Account is not Activated ....";
var xz = (from n in db.Auths
where n.Email == xr.Email && n.Password == xr.Password && n.Active == aut.Active
select n).FirstOrDefault();
if (xz != null)
{
result = "Your Account Activated....";
}
}
}
return result;
}
And this:
public ActionResult Login(Auth aut)
{
if (ModelState.IsValid)
{
string result = objrepo.validateUser(aut);
ViewBag.Success = result;
}
return View();
}
Change return type from void to string in validateUser method of repo.cs file.
Return message from method to controller.
i.e.
In controller file
public ActionResult Login(Auth aut)
{
if (ModelState.IsValid)
ViewBag.msg = objrepo.validateUser(aut);
else
ViewBag.msg = "Invalid.....";
return View();
}
Use ViewBag.msg in view file.
Thanks,
Hiral Shah
I'am trying create some validation for file size. My code:
[HttpPost]
public ActionResult Index(FotoModel model)
{
TryUpdateModel(model);
if (ModelState.IsValid)
{
if (model != null && model.File != null)
{
var fileName = Path.GetFileName(model.File.FileName);
var fileExtension = Path.GetExtension(fileName);
long fileSize = new FileInfo(fileName).Length;
fileName = "file" + fileExtension;
var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
if (fileSize < 55000)
{
model.File.SaveAs(path);
model.link = fileName.ToString();
}
else
{
ViewData["Size"] = "Akceptowane pliki: jpg, jpeg, png o maksymalnym rozmiarze 50 KB";
}
return View(model);
}
}
return View(model);
}
And in this line:
long fileSize = new FileInfo(fileName).Length;
I'am receiving error: "File cannot be found". Do You know how can I resolved this ?
In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-
public ActionResult Index(FotoModel model, HttpPostedFileBase file)
{
if (file != null)
{
int byteCount = file.ContentLength; // <---Your file Size or Length
.............
.............
}
}
What you are looking is a ContentLength
public ActionResult Index(FotoModel model)
{
if (model != null && model.File != null)
{
var fileSize = model.File.ContentLength;
}
}