Displaying Files Name and Link to download in mvc - asp.net-mvc-3

I have files saved in a Project Folder
D:\Maarjaa\Marjaa\Content\Uploads
Now I want to Display name of these files( not the full URL)
as
lakes of kaghan.jpg
lakes of gilgit.jpg
not as
D:\Maarjaa\Marjaa\Content\Uploads\lakes of kaghan.jpg
Additionally I want to give download links to thes files, so that a user can download these files

Many different ways to do this. Here's one:
Create a class for your files
public class Image
{
public string Name { get; set; }
public string Path { get; set; }
}
and a view model class
public class ViewModel
{
public List<Image> Images { get; set; }
public string Path { get; set; }
}
Then in your controller, populate the view model and the name and path properties for each Image object in the list. You'll need to import the System.IO namespace.
public ActionResult DisplayFilesForDownload( )
{
var viewModel = new ViewModel
{
Path = #"D:\Maarjaa\Marjaa\Content\Uploads",
Images = new List<Image>()
};
var paths = Directory.GetFiles(viewModel.Path).ToList();
foreach (var path in paths)
{
var fileInfo = new FileInfo( path );
var image = new Image
{
Path = path, Name = fileInfo.Name
};
viewModel.Images.Add(image);
}
return View( viewModel);
}
And the method to allow downloads. I am assuming all your files are images. If not, just adjust the MediaTypeName as needed.
public FileResult Download(string filePath, string fileName)
{
var file = File(filePath, System.Net.Mime.MediaTypeNames.Image.Jpeg, fileName);
return file;
}
and finally the view. Image.Name is used to display the shortened file name and Image.Path is used to tell the download method where to fetch the file from.
#model FullyQualified.Path.ToYour.ViewModel
#foreach (var image in Model.Images)
{
<p>#Html.ActionLink(image.Name, "Download", "ControllerName", new{filePath = image.Path, fileName = image.Name}, null)</p>
}
Hope this helps get you on your way.

I did it, In my View
<ul>
#foreach(var Item in(IEnumerable<Marjaa.Data.MultimediaFile>) ViewData["Files"])
{
<li>#System.IO.Path.GetFileName(Item.MultimediaFileUrl) </li>
}
</ul>
From my Controller Just Sent a list to View
IList<MultimediaFile> list = d.MultimediaFiles.Where(l => l.MultmediaId == id).ToList();
ViewData["Files"] = list;

Related

LINQ result is not showing as expected

I'm trying to query for a particular column & to show the item list in view properly one after another. Here is my code:
Controller:
public ActionResult ShowImage()
{
using (var context = new ImageTrialDBEntities())
{
var pathlist = (from s in context.Images
select s.ImageLink).ToList();
var model = new ImageModel();
model.ImageList = pathlist;
return View(model);
}
}
Model:
public class ImageModel
{
public string Image { get; set; }
public IList<string> ImageList { get; set; }
}
View:
<div>
#foreach (var s in Model.ImageList)
{
#Html.DisplayFor(x=>x.ImageList)
<br />
}
</div>
The list is showing like this:
I would like to show one at a time with a break in between. Please help.
Replace
#Html.DisplayFor(x=>x.ImageList)
with
#Html.DisplayFor(x=>s)
You have 2 loops in the view code. Try just printing out the variable s.

How to delete a Record from a List of files in a model in MVC3?

Hi all i have a TextBox and a Fileupload controll and a Table to show the uploaded Files...and i have a delete link in my table..so that user can delete any of the uploaded files before clicking on submit button....for this i have model
public BugModel()
{
if (ListFile == null)
ListFile = new List<BugAttachment>();
}
public List<BugAttachment> ListFile { get; set; }
}
public class BugAttachment
{
public string FileName { get; set; }
public int BugAttachmentID { get; set; }
public string AttachmentName { get; set; }
public int BugID { get; set; }
public string AttachmentUrl { get; set; }
public string AttachedBy { get; set; }
public string ErrorMessage { get; set; }
}
when ever user uploads a file i keep them in Listfile list and show them in table..now what i want is i want to delete the uploaded file from server and from the Listfile also
..i had succede deleting the file from uploaded files folder ...now i want to remove the AttachmentName and AttachmentUrl from my ListFile also when ever user clicks on delete link..how should i do this..any ideas are much appreciated
this is what i had done till now
public ActionResult Delete(string FileName, BugModel model)
{
if (Session["CaptureData"] == null)
{
}
else
{
model = (BugModel)Session["CaptureData"];
}
char DirSeparator = System.IO.Path.DirectorySeparatorChar;
string FilesPath = ";" + FileName;
string filenameonly = name + Path.GetFileName(FilesPath);
string FPath = "Content" + DirSeparator + "UploadedFiles" + DirSeparator + filenameonly;
// Don't do anything if there is no name
if (FileName.Length == 0) return View();
// Set our full path for deleting
string path = FilesPath + DirSeparator;
// Check if our file exists
if (System.IO.File.Exists(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + FPath)))
{
// Delete our file System.IO.File.Delete(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + FPath));
}
return View("LoadBug");
}
If the FileName is unique, you can create a new List of BugAttachments objects and exclude a particular object with the specified FileName
List<BugAttachment> allBugAttachemnts=GetAllAttachmentsFromSomeWhere();
List<BugAttachment> newBugAttachments = allBugAttachemnts.ListFile.
Where(x => x.FileName!= FileName).ToList();
Now newBugAttachments will have the Items after deletion.
You may also useRemoveAll method which updates the original List
allBugAttachemnts.RemoveAll(x => x.FileName!= FileName);
Assuming GetAllAttachmentsFromSomeWhere method returns a List of Available BugAttachment objects for the specified BugModel and FileName is the parameter which has the FileName to be deleted

Display Template For Generics - View is not found

I have the following classes:
public class Widget
{
public string Name { get; set; }
}
GenericModel
public class GenericModel<T>
{
public List<T> Data { get; set; }
}
My Controller action is:
public ActionResult Simple()
{
var model = new GenericModel<Widget>()
{
Data = new List<Widget>
{
new Widget {Name = "a"}
}
};
return View(model);
}
And my view is:
#model MyApp.GenericModel<MyApp.Widget>
#{
ViewBag.Title = "Simple";
}
<h2>Simple</h2>
#Html.DisplayFor(m=>m)
I have a file called GenericModel.cshtml in Views/Shared/DisplayTemplate folder:
#model MyApp.GenericModel<MyApp.Widget>
<ul>
#for (int i = 0; i < Model.Data.Count; i++ )
{
<li>
#Html.EditorFor(m=> Model.Data[i].Name)
</li>
}
</ul>
This view can not be found. I see when I print out the name of the type of my model I get "GenericModel1". Seeing that, I renamed my template "GenericModel1.cshtml". This seems like a bit of a hack, is there an easier way to find this display template without resorting to this?
You have to set it in your viewstart:
#Code
Layout = "~/Views/Shared/DisplayTemplate.cshtml"
End Code
Note: The above is VB.
You can also pass it via your controller like this:
public ActionResult Simple()
{
var model = new GenericModel<Widget>()
{
Data = new List<Widget>
{
new Widget {Name = "a"}
}
};
return View("", "DisplayTemplate", model);
}

How to use ViewBag as list in MVC3

i need to use ViewBag as list inside another ViewBag and i am not understanding how should i do that.
here is my code:
List<string> srclist = new List<string>();
foreach(var item in candidateportfolio)
{
if(item.PortfolioID!=0 && item.ChandidateID!=0)
{
string filepath = Server.MapPath("~/ePortfolio/PortFolioContent/" + HobbyDetailID + "/Assignments/Exhb_" + item.PortfolioID + "_" + item.ChandidateID + ".jpg");
if (System.IO.File.Exists(filepath))
{
srclist.Add(filepath);
}
}
}
ViewBag.Thumbnail = srclist;
candidateportfolio is an object of the class CandidatePortfolio.I fetch the data in the class and check whether its fields are not empty.Then i add the filepath to the list and assign list to Viewbag
Then in View i use it like this:
#foreach (var item in ViewBag.Thumbnail as List<string>)
{
<img src="#item" title="Learner:#ViewBag.FirstName" width="150px" height="150px" border="5" style="align:right;margin:10px"/>
}
Now the problem is i also want to fetch ViewBag.FirstName as list.and i cannot run another list in this.Please tell me how should i do this.
If you want a list containing both FirstName and the path to, say, a photo you can create a new class:
public class ThumbnailModel
{
public string FirstName { get; set; }
public string PhotoPath { get; set; }
}
Now you can add a List<Thumbnail> to the ViewBag.
But I would suggest just creating a strongly typed view with a relvant model containing a List<Thumbnail> property.
user1274646,
your best bet here is to create a public class that contains both the exisiting thumbnail element plus an additional FirstName property. Here's how this might look:
public class CandidateItem{
public string FirstName {get; set;}
public string Filepath {get; set;}
}
then, in your loop, create a new CandidateItem and add it to the list (i.e. List). Here's the amended code:
List<CandidateItem> srclist = new List<CandidateItem>();
foreach(var item in candidateportfolio)
{
if(item.PortfolioID!=0 && item.ChandidateID!=0)
{
CandidateItem candItem = new CandidateItem();
candItem.Filepath = Server.MapPath("~/ePortfolio/PortFolioContent/" + HobbyDetailID + "/Assignments/Exhb_" + item.PortfolioID + "_" + item.ChandidateID + ".jpg");
candItem.FirstName = item.FirstName;
if (System.IO.File.Exists(filepath))
{
srclist.Add(candItem);
}
}
}
ViewBag.Thumbnail = srclist;
then use it in the view as:
#foreach (var item in ViewBag.Thumbnail as List<CandidateItem>)
{
<img src="#item.Filepath" title="Learner:#item.FirstName" width="150px" height="150px" border="5" style="align:right;margin:10px"/>
}

Convert that image in thumbnail and save both the images in asp.net-mvc3

upload image by upload control and convert that image in thumbnail and save both file actual image in image folder and thumbnail image in thumbnail Image folder in asp.net-mvc3
I use a 3rd party library called Image Resizer. I struggled with the uploading of images and retaining quality, this library helped me out alot.
In your view:
#model YourProject.ViewModels.ProductImageUploadCreateViewModel
#using (Html.BeginForm("Upload", "ProductImage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageFile1" id="ImageFile1">
}
Your controller:
public class ProductImageController : Controller
{
[HttpPost]
public ActionResult Upload(ProductImageUploadCreateViewModel viewModel)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
if (viewModel.ImageFile1 != null)
{
UploadImage(viewModel.ProductId, "1", viewModel.ImageFile1);
}
// Return to where ever...
}
}
Your upload method:
private void UploadImage(int productId, string imageNo, HttpPostedFileBase imageFile)
{
string uploadPath = Server.MapPath("~/Assets/Images/Products/" + productId);
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
Dictionary<string, string> versions = new Dictionary<string, string>();
versions.Add("_m", "width=150&height=150&scale=both&format=jpg"); // Medium size
string filePrefix = productId + "_" + imageNo;
versions.Add("_s", "width=90&height=90&scale=both&format=jpg"); // Small size
versions.Add("_l", "width=300&height=300&scale=both&format=jpg"); // Large size
foreach (string fileSuffix in versions.Keys)
{
// Generate a filename
string fileName = Path.Combine(uploadPath, filePrefix + fileSuffix);
// Let the image builder add the correct extension based on the output file type
fileName = ImageBuilder.Current.Build(imageFile, fileName, new ResizeSettings(versions[fileSuffix]), false, true);
}
}
Have a look on their website, there are a couple of samples that you can work through. I hope this helps :)

Resources