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
}
}
Related
I am sending months (get the value from File path) and File path to the MVC view so I can show a List of the month that is linked to the File to download it like this:
OCT(that is linked to file path)
Nov (that is linked to file path)
December (that is linked to file path)
This is my Controller C# code:
public ActionResult Help()
{
var releaseNoteFiles = Directory.GetFiles(Server.MapPath("~/Content/ReleaseNotes"));
List<string> month = new List<string>();
foreach (var releaseNoteFile in releaseNoteFiles)
{
month.Add(new Regex("([^A-Z]*)([a-zA-Z]*)").Match(Path.GetFileNameWithoutExtension(releaseNoteFile).Split('.').Last()).Groups[2].Value);
}
ViewBag.releaseNoteFilesmonth = month; /Has October,Nov,...
ViewBag.releaseNoteFiles = releaseNoteFiles; /Has Path to the File
return View();
}
This is my view that I have a problem with how to send 2 lists (Filename and Path) This code shows the list 2 times.
#foreach (var item in ViewBag.releaseNoteFilesmonth)
{foreach (var item2 in ViewBag.releaseNoteFiles)
{
#item #item
<br />
}
}
It seems you want to print the month and the monthfile with hyperlink on the view, see the below code if that sorts you out.
#foreach (var item in ViewBag.releaseNoteFilesmonth)
{
var matchedmonthfile = (ViewBag.releaseNoteFiles as string[]).Where(x => x.Contains(item)).FirstOrDefault();
#item #matchedmonthfile
<br />
}
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
I'm writing an ASP.NET web app (university task for exam). I have a database which has columns like Id, Name, Age, SumNote. First of all I had to make a partial view with top 5 students in database:
This method to get top 5 students
public class HomeController : Controller
{
StudentContext db = new StudentContext();
public ActionResult ShowTopFive ()
{
var allStudents = db.Students.OrderByDescending(s => s.SumNote).Take(5);
return PartialView(allStudents);
}
}
This is the patrial View:
#model IEnumerable<Univercity.Models.Student>
<div id="results">
<h4>Best 5 students</h4>
<ul>
#foreach (var item in Model)
{
<li>#item.Name, Summ of notes: #item.SumNote</li>
}
</ul>
</div>
and with this one I got the list of students in my webpage
<div>
<h5>Show top 5 students</h5>
</div>
<div>
#using (Ajax.BeginForm("ShowTopFive", new AjaxOptions { UpdateTargetId = "results" }))
{
<input type="submit" value="Show"/>
}
<div id="results"></div>
</div>
the output result looks like this:
Ivanov Mikhail, Summ of notes: 16
Kozlov Pete, Summ of notes: 12
Mary Ann, Summ of notes: 11
I also need to save it as text file. Can't figure out how? May be there is a way to change something in Ajax code?
Thanks in advance. Hope someone know how to do it. Google didn't help
You could create a controller action method which uses FileStreamResult by iterating the list created from ToList() and write necessary property values into a stream, then use Controller.File() overload which accepts stream to let user download text file:
public ActionResult GetTextFile()
{
var topFiveStudents = db.Students.OrderByDescending(s => s.SumNote).Take(5).ToList();
if (topFiveStudents != null && topFiveStudents.Count > 0)
{
string fileName = "something.txt";
// create a stream
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
foreach (var students in topFiveStudents)
{
// iterate the list and write to stream
sw.WriteLine(string.Format("{0}, Sum of notes: {1}", students.Name, students.SumNote));
}
sw.Flush();
ms.Position = 0;
// return text file from stream
return File(ms, "text/plain", fileName);
}
else
{
// do something else
}
}
Afterwards, create an anchor link pointed to that action method mentioned above inside partial view:
#Html.ActionLink("Export to TXT", "GetTextFile", "ControllerName")
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);
} });});
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..