adding photo and model - c#

I am new to asp.net core. I am facing a problem when uploading a file(image) with my model.
the viewmodel :
namespace WebApplication1.ViewModels
{
public class HotelViewModel
{
public String NomHotel { get; set; }
public String NomAgence { get; set; }
public String Filepath{ get; set; }
}
}
this is the cshtml :
#model WebApplication1.ViewModels.HotelViewModel
<form novalidate method="post" enctype="multipart/form-data" asp-
controller="Hotel" asp-action="Hotel">
<div id="parent">
<div id="wide" class="col-lg-4">
<div asp-validation-summary="ModelOnly"></div>
<div class="form-group">
<label asp-for="NomHotel"></label>
<input asp-for="NomHotel" class="form-control" />
<span asp-validation-for="NomHotel"></span>
</div>
<div class="form-group">
<label asp-for="NomAgence"></label>
<input asp-for="NomAgence" class="form-control" />
<span asp-validation-for="NomAgence"></span>
</div>
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="files" multiple class="btn" />
</div>
<div id="#rest">
<div class="form-group">
<input type="submit" value="Ajouter" class="btn btn-lg btn-
success ahbat" />
</div>
</div>
</div>
</div>
and this is the controller :
[HttpPost]
public IActionResult Hotel(HotelViewModel mod)
{
Hotel hotel = new Hotel
{
NomAgence = mod.NomAgence,
NomHotel = mod.NomHotel
};
var newFileName = string.Empty;
if (HttpContext.Request.Form.Files != null)
{
var fileName = string.Empty;
string PathDB = string.Empty;
var files = HttpContext.Request.Form.Files;
foreach (var file in files)
{
if (file.Length > 0)
{
//Getting FileName
fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
//Assigning Unique Filename (Guid)
var myUniqueFileName = Convert.ToString(Guid.NewGuid());
//Getting file Extension
var FileExtension = Path.GetExtension(fileName);
// concating FileName + FileExtension
newFileName = myUniqueFileName + FileExtension;
// Combines two strings into a path.
fileName = Path.Combine(_environment.WebRootPath, "HotelImg") + $#"\{newFileName}";
// if you want to store path of folder in database
PathDB = "demoImages/" + newFileName;
hotel.Piscine = newFileName;
using (FileStream fs = System.IO.File.Create(fileName))
{
file.CopyTo(fs);
fs.Flush();
}
}
}
}
IH.Create(hotel);
return View();
}
as said I have tried different combinations of code but I always get the file or the model never both and I need both of them. This is the most correct code I can show you sorry if it is not too clear.

Related

An item with the same key has already been added. Key: [0, SEX]

When I am trying to import an excel more than 33 columns I have this error.
An item with the same key has already been added. Key: [0, SEX]
[0,SEX] is my 34th column
I am converting file to an Isheet object. It's working fine when it's under 33 columns.
Also It's working on a different project. I am using it exactly same way here too. I checked versions of some packages but couldn't find the problem.
This is my controller.
public async Task<IActionResult> YeniUyeAktarimUpload()
{
try
{
IFormFile file = Request.Form.Files[0];
string folderName = "UploadExcel";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
Stream stream = file.OpenReadStream();
using (stream)
{
ISheet sheet;
string sFileExtension = Path.GetExtension(file.FileName).ToLower();
if (sFileExtension == ".xls")
{
HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
else
{
XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //I GET ERROR HERE
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
}
await _aktarimlarService.YeniUyeAktarim(sheet);
return RedirectToAction("YeniUyeAktarim","Aktarimlar");
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
TempData["ErrorMessage"] = "Duyurular getirilirken hata oluştu. Lütfen daha sonra tekrar deneyiniz. ";
return RedirectToAction("Error", "HomeKurum", new { returnUrl = "/Aktarimlar/YeniUyeAktarim" });
}
}
and this is my view
<section class="content">
<div class="card card-primary card-outline">
<div class="card-header">
<h2 class="card-title">Yeni Üye Aktarım</h2>
</div>
<!-- /.card-header -->
<div class="card-body">
<form asp-controller="Home" asp-action="Export">
<div class="container">
<div class="row">
<div class="col-md-4">
<input type="file" id="fileupload" name="files" class="form-control" />
</div>
<div class="col-md-3">
<input type="button" name="Upload" value="Upload" id="btnupload" class="btn btn-primary" />
Download
</div>
<div class="col-md-5">
<input type="submit" name="Export" value="Create and Export" id="btnExport" class="btn btn-primary" asp-action="Export" />
</div>
</div>
<div class="clearfix"> </div>
<div class="row">
<div id="divPrint"></div>
</div>
</div>
</form>
<a class="text-danger" href="~/Downloads/AKTARIM_TASLAK/YeniUyeAktarim.xlsx">Taslak indir</a>
<img width="50" height="40" src="~/images/excel-indir.png" />
#if (TempData.ContainsKey("ErrorMessage"))
{
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
#TempData["ErrorMessage"]
</div>
}
</div>
</div>
And this is my jquery code
<script type="text/javascript">$(function () {
$('#btnupload').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fileupload').val();
if (filename.length == 0) {
alert("Please select a file.");
return false;
}
else {
var extension = filename.replace(/^.*\./, '');
if ($.inArray(extension, fileExtension) == -1) {
alert("Please select only excel files.");
return false;
}
}
var fdata = new FormData();
var fileUpload = $("#fileupload").get(0);
var files = fileUpload.files;
fdata.append(files[0].name, files[0]);
$.ajax({
type: "POST",
url: "/Aktarimlar/YeniUyeAktarimUpload",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: fdata,
contentType: false,
processData: false,
success: function (response) {
if (response.length == 0)
alert('Some error occured while uploading');
else {
$('#divPrint').html(response);
}
},
error: function (e) {
$('#divPrint').html(e.responseText);
}
});
})
$('#btnExport').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fileupload').val();
if (filename.length == 0) {
alert("Please select a file then Import");
return false;
}
});
});</script>
Thanks for your help..

How to retrieve old Path image when we not update c# mvc

I am working on update form, my scenario is I don't want to update new image I just want to update only other data then submit when I submit the form "image URL" shows the null value not show the old path of the image.i have tried this code which I am sharing you kindly tell me how to resolve this issue.
Just give the hint of code then I will resolve this.
Model
public class ProductViewModel{
public string ImageUrl { get; set; }
[NotMapped]
public HttpPostedFileBase imageUpload { get; set; }
public ProductViewModel()
{
ImageUrl = "~/Scripts/imageloading/image.jpg";
}
}
c#
public ActionResult AddOrEditProducts(ProductViewModel prod)
{
Product pro = new Product();
ProductDetail p_spec = new ProductDetail();
var result = new jsonMessage();
try
{
List<ProductType> PTlist = _IproductType.PTList();
ViewBag.Ptlist = new SelectList(PTlist, "PType_ID", "P_Name");
//Product Color List
List<P_Color> pColorList = _IProductColor.PColorlist();
ViewBag.pColor_List = new SelectList(pColorList, "C_ID", "C_Name_OR_Code");
List<P_Size> pSizeList = _ISize.pSizeList();
ViewBag.pSizeLists = new SelectList(pSizeList, "S_ID", "S_Size");
if (prod.imageUpload != null) // shows null here
{
string filename = Path.GetFileName(prod.imageUpload.FileName);
string _filename = DateTime.Now.ToString("yymmssff") + filename;
string extension = Path.GetExtension(prod.imageUpload.FileName);
prod.ImageUrl= "~/upload/" + _filename;
if (extension.ToLower() == ".jpeg" || extension.ToLower() == ".jpg" || extension.ToLower() == ".png")
{
if (prod.imageUpload.ContentLength <= 1000000)
{
prod.imageUpload.SaveAs(Path.Combine(Server.MapPath("~/upload/"), _filename));
p_spec = new ProductDetail();
p_spec.ProductID = prod.ProductID;
p_spec.OS = prod.OS.Trim();
p_spec.DualSim = prod.DualSim.Trim();
p_spec.Camera = prod.Camera.Trim();
p_spec.TouchScreen = prod.TouchScreen.Trim();
p_spec.ScreenSize = prod.ScreenSize.Trim();
p_spec.ProcessorType = prod.ProcessorType.Trim();
p_spec.RAM = prod.RAM.Trim();
p_spec.InternalMemory = prod.InternalMemory.Trim();
p_spec.Wifi = prod.Wifi.Trim();
p_spec.BatteryLife = prod.BatteryLife.Trim();
p_spec.Other = prod.Other.Trim();
p_spec.PDescription = prod.PDescription.Trim();
p_spec.Model = prod.Model.Trim();
p_spec.Condition = prod.Condition.Trim();
p_spec.Discount = prod.Discount;
p_spec.ImageUrl = prod.ImageUrl;
}
else
ViewBag.sizemsg = "Size Limit accessed ";
}
else
ViewBag.fileformat = "File is not Format is not Correct";
pro = new Product();
pro.ProductID = prod.ProductID;
pro.PName = prod.PName.Trim();
pro.ManificturedPrice = prod.ManificturedPrice;
pro.P_SizeID = prod.P_SizeID;
pro.P_Color_ID = prod.P_Color_ID;
pro.PType_ID = prod.PType_ID;
pro.UnitWeight = prod.UnitWeight;
pro.UnitInStock = prod.UnitInStock;
}
if (prod.ProductID == 0)
{
_IProducts.AddOrEditProducts(pro, p_spec);
result.Message= "Product has been saved success..";
result.Status = true;
ModelState.Clear();
}
else
{
_IProducts.AddOrEditProducts(pro, p_spec);
result.Message = "Product Update Successfully";
result.Status = true;
ModelState.Clear();
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
result.Message = "We are unable to process your request at this time. Please try again later.";
result.Status = false;
}
}
return RedirectToAction("ProductsList");
}
View
<div id="tabimage" class="tab-pane">
<h3 class="mgtp-15 mgbt-xs-20"> Images</h3>
<div class="vd_panel-menu">
<input type="submit" value="Save Changes" class="btn vd_btn vd_bg-blue btn-icon btn-sm save-btn fa fa-save" id="btnSave" />
<button type="reset" value="Cancel" class="btn vd_btn vd_bg-blue btn-icon btn-sm save-btn fa fa-save" id="" />
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-lg-3 file_upload_label"> <span title="" data-toggle="tooltip" class="label-tooltip" data-original-title="Format JPG, GIF, PNG. Filesize 8.00 MB max."> Add a new image to this product </span> </label>
<div class="col-lg-9">
<div class="col-lg-5">
<span class="btn vd_btn vd_bg-green fileinput-button">
<i class="glyphicon glyphicon-plus"></i> <span>Add files...</span>
<input type="file" name="imageUpload" multiple id="imageUpload" onchange="ShowimahePreview(this,document.getElementById('previewImage'))" />
</span>
</div>
<div class="col-lg-4">
<img src="#Url.Content(Model.ImageUrl)" alt="Alternate Text" height="150" weight="" id="previewImage" />
</div>
</div>
</div>
</div>
</div>

Error: No parameterless constructor defined for this object

I am trying to use Action-[HttpPost] in my ASP MVC project however the Post Action doesn't seems to work.After Submit button Page will showing Error.
Following is my model:
public class bcSlider
{
public int sliderID { get; set; }
public string sliderImage { get; set; }
}
Following is my ManageOperations:
public class MngSlider
{
public int insertSlider(bcSlider obj)
{
int condition = 0;
try
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ospDB"].ConnectionString);
SqlCommand cmd = new SqlCommand("usp_InsertConfrence", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#SliderImage", obj.ImageName);
if (con.State.Equals(ConnectionState.Closed))
con.Open();
condition = cmd.ExecuteNonQuery();
con.Close();
if (condition > 0)
{
return 1;
}
else
{
return 0;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
Following is Controller:
public class AdminSliderController : Controller
{
bcSlider modelSlider = new bcSlider();
MngSlider objSlider = new MngSlider();
//---------------INSERT---------------//
// GET: /AdminSlider/AddSlider
public ActionResult AddSlider()
{
bcSlider mSlider = new bcSlider();
return View(mSlider);
}
// POST: /AdminSlider/AddSlider
[HttpPost]
public ActionResult AddSlider(HttpPostedFile file, bcSlider mSlider)
{
if (ModelState.IsValid)
{
//File Available Verification
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName); //FileName
string fileExtension = Path.GetExtension(fileName); //FileExtension
//Extension Verification
if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".jpeg" || fileExtension.ToLower() == ".png" || fileExtension.ToLower() == ".pdf" || fileExtension.ToUpper() == ".JPG" || fileExtension.ToUpper() == ".JEPG" || fileExtension.ToUpper() == ".PNG" || fileExtension.ToUpper() == ".PDF")
{
//FileSize Verification
int length = file.ContentLength;
if (length <= 1000)
{
string filepath = Path.Combine(Server.MapPath("~/ImagesDirectory/"), fileName); //FilePath
file.SaveAs(filepath);
objSlider.insertSlider(mSlider); //Insert to DB
ViewBag.Message = "<script>alert('File Inserted Successfully !')</script>";
ModelState.Clear();
}
else
{
ViewBag.SizeMessage = "<script>alert('Size Should be of 1MB !')</script>";
}
}
else
{
ViewBag.ExtensionMessage = "<script>alert('File Not Supported !')</script>";
}
}
else
{
ViewBag.Message = "<script>alert('Invalid File !')</script>";
}
}
else
{
ViewData["result"] = "Registration Not Successful";
}
return RedirectToAction("AddSlider");
}
}
}
Following is htmlcs:
#model OspWebsite.Models.bcSlider
#{
ViewBag.Title = "AddSlider";
Layout = "~/Views/Shared/LayoutAdmin.cshtml";
}
<div class="content-header">
<!-- Page Name -->
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0 text-dark">Slider</h1>
</div><!-- /.col -->
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item active">Slider</li>
</ol>
</div><!-- /.col -->
</div><!-- /.row -->
</div>
#Html.Raw(ViewBag.Message)
#Html.Raw(ViewBag.SizeMessage)
#Html.Raw(ViewBag.ExtensionMessage)
#using (Html.BeginForm("AddSlider", "AdminSlider", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<!-- Input Forms -->
<div class="row">
<div class="offset-md-1 mt-5 col-md-10">
<div class="card card-success">
<div class="card-header">
<h3 class="card-title">Add New Slider</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-widget="maximize"><i class="fas fa-expand"></i></button>
<button type="button" class="btn btn-tool" data-widget="collapse"><i class="fas fa-minus"></i></button>
</div>
<!-- /.card-tools -->
</div>
<!-- /.card-header -->
<div class="card-body">
<div class="card-body">
<div class="form-group">
<div class="col-sm-12 ">
<label for="inputEmail3" class="col-sm-4 control-label">Select Slider</label>
<div class="custom-file">
<label class="custom-file-label" for="exampleInputFile"></label>
<input type="file" name="sliderImage" value=#Model.sliderImage class="custom-file-input" id="exampleInputFile">
</div>
</div>
</div>
</div>
<!-- /.card-body -->
</div><div class="card-footer">
<button type="submit" class="btn btn-success">Upload</button>
<button type="submit" class="btn btn-default float-right">Cancel</button>
</div>
<!-- /.card-footer -->
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<!-- /.col -->
</div>
}
</div>
The GET Action is Calling But POST Action is Showing Error.
i am inserting Image in Database.
You are having the error because of the parameter you are passing in the controller HttpPostedFile
HttpPostedFileBase and HttpPostedFile
are definitely not the same.
Change your method to
[HttpPost]
public ActionResult AddSlider(HttpPostedFileBase sliderImage, bcSlider mSlider)
{
//your code here.
}
Notice that I used sliderImage because that was also what you have in your form.
Again Your form, which I don't know if it was a typo error is setting the value of a file-input
<input type="file" name="sliderImage" value=#Model.sliderImage class="custom-file-input" id="exampleInputFile">
You are not supposed to do that.
Again and on lighter note, if it is also not a typo, you don't have any attribute in you class obj.ImageName but you have the below in your insertSlider method
cmd.Parameters.AddWithValue("#SliderImage", obj.ImageName);
For more on HttpPostedFileBase and HttpPostedFile and see here
That's all for now.

access input value in webAPI from post

I use the following code to upload files using a webAPI, the file upload part works fine but how can I access all additional input values and hidden input values from the post?
[HttpPost]
public async Task<object> UploadFile()
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data/Temp/"));
try
{
await Request.Content.ReadAsMultipartAsync(streamProvider);
foreach (MultipartFileData fileData in streamProvider.FileData)
{
var fileName = "";
if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
{
fileName = Guid.NewGuid().ToString();
}
fileName = fileData.Headers.ContentDisposition.FileName;
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
{
fileName = fileName.Trim('"');
}
if (fileName.Contains(#"/") || fileName.Contains(#"\"))
{
fileName = Path.GetFileName(fileName);
}
File.Move(fileData.LocalFileName, Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), Path.GetDirectoryName(fileName) + Guid.NewGuid() + Path.GetExtension(fileName)));
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
And here is the form I am using for posting the file.
<form name="form1" method="post" enctype="multipart/form-data" action="api/upload">
<div>
<label for="caption">Image Caption</label>
<input name="caption" type="text" />
</div>
<div>
<input type="hidden" value="secretvalue"/>
<label for="image1">Image File</label>
<input name="image1" type="file" />
</div>
<div>
<input type="submit" value="Submit" />
</div>

File is not uploading in ASP.Net MVC

Hi to all of you I am facing a problem on uploading a file and saving it into a folder here is my view
<div class="admin-empty-dashboard">
#using (Html.BeginForm("UploadResumes", "Employee", new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="icon">
<i class="ion-ios-book-outline"></i>
</div>
<h4>Welcome #Model.FullName!</h4>
<p>#ViewBag.Error</p>
<div class="form-group bootstrap-fileinput-style-01">
<label>Upload Resume</label>
<input type="file" name="file" required="required" class="btn btn-primary" style="margin-left:265px" accept="application/msword,text/plain, application/pdf">
<span class="font12 font-italic">** File must not bigger than 2MB</span>
</div>
<input type="submit" name="name" class="btn btn-primary" value="UploadResumes" />
}
</div>
and here is my controllers action problem is that it HttpPostedFileBase object value is always null and i ran Request.Files.Count it's also giving me zero where is problem?
public ActionResult UploadResumes(HttpPostedFileBase file)
{
if (Session["UserID"] != null && Session["UserName"] != null && Session["EmployeeID"] != null)
{
int id = Convert.ToInt32(Session["EmployeeID"]);
string[] allowedExtenssions = new string[] { ".pdf", ".doc", ".docx" };
string cvPath = "~/cvs/Employee_cvs/";
if (!Directory.Exists(Server.MapPath(cvPath)))
Directory.CreateDirectory(Server.MapPath(cvPath));
MyDbContext db=new MyDbContext();
tblEmployee employee = (from s in db.tblEmployees where s.UserId == id select s).FirstOrDefault();
// HttpPostedFileBase cv = Request.Files["CV"];
if (file != null)
{
if (file.ContentLength > 0)
{
string ext = Path.GetExtension(file.FileName);
if (allowedExtenssions.Contains(ext.ToLower()))
{
string fileName = DateTime.Now.Ticks + ext;
string filePath = cvPath + fileName;
string serverPath = Server.MapPath(filePath);
file.SaveAs(serverPath);
employee.cvUrl = filePath;
}
}
ViewBag.Error = "Some Error Occured";
}
return RedirectToAction("Dashboard");
}
else
{
return RedirectToAction("Login", "User");
}
}
Update like below and check
#using (Html.BeginForm("UploadResumes", "Employee",FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
Also
[HttpPost]
public ActionResult UploadResumes(HttpPostedFileBase file)
{
}
Try changing your parameters on your controller to
public ActionResult UploadResumes(Model yourModel, HttpHostedFileBase file)
In most of my controllers that require a file for upload, are usually array based. Make you function parameters an array like this:
public ActionResult UploadResumes(HttpPostedFileBase[] files){
}

Categories

Resources