How to get multiselected files from input to c# object - c#

I want to get all files that are selected in input file to c# object, but it select only one file from mutiselected files to display in text box.
Input file to select multiple files:
<input type="file" name="File2" id="File2" accept="image/*" multiple/>
Input text to display all selected files:
#Html.EditorFor(model => model.DocumentName, new { htmlAttributes = new { #id = "documentName", #class = "form-control" } })
Model:
[Display(Name = "DocumentName", ResourceType = typeof(Resources.Resources))]
public override string DocumentName
{
get { return base.DocumentName; }
set { base.DocumentName = value; }
}
What changes are required in my code, to resolve it?

Please Add this in your script. It will works when selecting files on upload i.e OnChange Functionality. Please Try it and Let me know.
$("document").ready(function(){
$("#File2").change(function() {
var files = $(this)[0].files;
for (var i = 0; i < files.length; i++) {
$("#documentName").val(files[i].name);
} });});

Related

How to show FIleName and download link for file using ASP.Net MVC?

I am having trouble in rendering the files listed in the Folder. I am able to display the URL for the files listed in folder, but instead of Link I want it to show FileName and not the URL. Also, I am looking to be able to add a hyperlink to respective files so that can be downloaded from the Folder.
Model Class
public string AgentName { get; set; }
public string DealType { get; set; }
public HttpPostedFileBase[] files { get; set; } //Used to upload multiple files or images
Action Method to call
public ActionResult DealInfo(int id)
{
using(Db db = new Db())
{
ManagementDeal deal = db.ManagementDeals.FirstOrDefault(x => x.DealId == id);
var dId = deal.DealId;
ViewBag.DealID = dId;
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/Uploads/Deals/" + id));
ViewBag.FilePath = filePaths;
View to render the Files from Folder
<div class="container-fluid">
<div class="row">
#foreach (string item in ViewBag.FilePath)
{
<div class="col-sm-2">
<div class="text-center">
<h1><i class="fas fa-file-alt text-warning"></i></h1>
#item<br />
</div>
</div>
}
</div>
</div>
So,
Show file name instead of the URL
should be able to download file on clicking Name of File.
Screen shot is here for my current View https://prnt.sc/1343b8d
Thank you in advance.
Managed to fix it with the below code in Controller Action
ViewBag.FilePath = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Deals/" + id ))
.Select(fn => Path.GetFileName(fn));
Using above render ViewBag in a View using foreach and can show the file name and download the file on click

How to show directory files in select using razor?

With my current below code I can get the files and output them in a select option but if the user submits the form without selecting a image it will give a error
" Object reference not set to an instance of an object."
I have merch_image in the model Required.
How do I make the below select using razor so it won't bypass the Required?
controller:
public ActionResult Create()
{
DirectoryInfo dirInfo = new DirectoryInfo(#"//uploads/stamp_images");
ViewBag.Message = dirInfo.GetFiles().ToList();
return View();
}
View:
<select class="form-control col-sm-3" id="merch_image" name="merch_image">
<option selected disabled="disabled">Select</option>
#foreach (var item in ViewBag.Message)
{
<option value="#item.Name"> #item.Name</option>
}
</select>
#Html.ValidationMessageFor(model => model.merch_image, "", new { #class = "text-danger" })
Try this code, first its find containing image folder and find which one you find
in folder,
string ImagePath = Server.MapPath("~/uploads/stamp_images");
string FileName = 'xyz' + ".png";
//check image file exist or not
var filters = new String[] { "png" };
var files = GetFilesFrom(ImagePath, filters, false);
foreach (var item in files)
{
if (item.Contains(FileName))
{
//return contains image
}
}

How to insert data into multiple tables in ASP. NET MVC. Entity Framework

I have two tables tblProduct & tblImages. tblImages will have multiple images for a product and has a foreign key related to tblProduct. I have a problem with inserting data into multiple tables.
This is my view code:
<!-- Text Boxes and dropdown lists for tblProduct above and below is for adding files to tblImages-->
<div class="col-md-10">
<input multiple type="file" id="file" name="file" />
</div>
and here is my controller's code:
public ActionResult AddProduct_Post([Bind(Include = "productName, productDescription, productPrice, productCategory")]tblProduct tblProduct,List<HttpPostedFileBase> file)
{
List<tblImage> prodImages = new List<tblImage>();
var path = "";
foreach (var item in file)
{
if (item != null)
{
tblImage img = new tblImage();
img.ImageFile = new byte[item.ContentLength];
img.ImageName = string.Format(#"{0}.JPG", Guid.NewGuid());
img.vend_ID = Convert.ToInt32(Session["userID"]);
item.InputStream.Read(img.ImageFile, 0, item.ContentLength);
path = Path.Combine(Server.MapPath("~/Content/img"), img.ImageName);
item.SaveAs(path);
prodImages.Add(img);
}
}
tblProduct.venodrID = Convert.ToInt32(Session["userID"]);
tblProduct.tblImages = prodImages;
if (ModelState.IsValid)
{
db.tblProducts.Add(tblProduct);
db.SaveChanges();
int latestProdID = tblProduct.productID;
foreach (tblImage tblImg in tblProduct.tblImages)
{
tblImg.prod_ID = latestProdID;
db.Entry(tblImg).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("DashBoard");
}
ViewBag.productCategory = new SelectList(db.tblCategories, "categoryID", "categoryName");
ViewBag.vendorGender = new SelectList(db.tblGenders, "genderId", "genderName");
return View();
}
I put a breakpoint on ModelState.IsValid and it is not going inside the if conditions and is returning back the same view without posting the data. Kindly tell me how to solve this issue
P.S: I am new to ASP.NET MVC
[Bind(Include =
you can the check parameter you bind in action method is similar what you defined in the View else you can remove the bind attribute and try this will help you to find what actually error is..

How to upload multiple files into C# and loop through them in MVC

I'm having a problem with uploading multiple files to C# and loop through them. I found a question with a similar problem but nobody answered it.
I upload multiple files through an html input. The file count passes through to my controller with the correct amount relative to the amount of files I selected. However when I try to loop through each of my files it loops through the first file relative to the file count. For example if I upload 3 files it loops through the first file 3 times or if I upload 5 files it loops through the first file 5 times. It should not do this. I want it to loop through each file individually. Please help!!! here is my code:
Razor View(I'm using a bootstrap library for fileinputs called bootstrap-filestyle):
#using (Html.BeginForm("Initial", "DataCapture", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<h4>Select files</h4>
<input type="file" multiple="multiple" id="fileToUpload" name="file">
</div>
<div>
<input type="submit" value="Capture" class="btn btn-default" />
</div>
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Initial(ClaimModel claimModel)
{
if (ModelState.IsValid)
{
//OtherCode
handleFile(Request.Files, c.ClaimID);
return RedirectToAction("Index", "ClaimFiles", new { id = c.ClaimID });
}
//OtherCode
}
private void handleFile(HttpFileCollectionBase Files, int ClaimID)
{
foreach (string fileName in Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//OtherCode
}
//OtherCode
}
I put break points on handleFile(Request.Files, c.ClaimID); and inside foreach (string fileName in Files){...}. As I said it correctly passes through the file count if I upload 3, 4, 5 or any amount of files however it only loops through the first file that amount of times and returns the first file multiple times as well. I need it to loop through and return each file individually. How do I do this correctly?
Use Request from server, here is one example:
for (int i = 0; i < Request.Files.Count; i++)
{
var fileDoc = Request.Files[i];
}
Or you can try something like this:
HttpPostedFileBase hpf = null;
foreach (string file in Request.Files)
{
hpf = Request.Files[file] as HttpPostedFileBase;
}

have problem with MVC, String not Showing in the Return View

in the Controller:
public ActionResult Create()
{
int i = 0;
string s = "";
bool unique = false;
while (!unique)
{
s = GenerateCode(i);
var CheckURLs = from x in db.QRCodeGs
where x.QRCodeShortString == s
select new { ShortCode = x.QRCodeShortString};
if (CheckURLs.Count() == 0)
{
unique = true;
}
else
{
i++;
}
}
return View(new QRCodeG { QRCodeShortString = s, QRCodeGenDate = DateTime.Today, LastEditDate = DateTime.Today, LastEditor = User.Identity.Name });
//return View();
}
Create.cshtml page:
<div class="editor-field">
#Html.EditorFor(model => model.QRCodeShortString)
#Html.ValidationMessageFor(model => model.QRCodeShortString) <br />(You make choose your own string or use this dynamically generated one)
</div>
Not sure exactly what the problem is, but here's a few things to check
Make sure the model is the proper type in the cshtml page. ie: #model QRCodeG
Make sure the variable 's' actually has something in it
Check your css (editor-field class) to make sure you aren't hiding it by mistake.
the first thing I would suggest is to move where you declare the model you are passing to the view, do something like
var qrCodeG = new QRCodeG { QRCodeShortString = s, QRCodeGenDate = DateTime.Today, LastEditDate = DateTime.Today, LastEditor = User.Identity.Name };
return qrCodeG;
then use the debugger to see if qrCodeG is being populated correctly.
if that works then try adding
<div> #model.QRCodeShortString </div>
to your view and see if that is outputting your data correctly
if that works look at what is going on in #Html.EditorFor(model => model.QRCodeShortString)

Categories