skip to Main Content

I have this model,and table i db with data

public class FileType
    {
        public int Id { get; set; }

        public string FileTypeName { get; set; }
    }

I have upload form and this viewmodel for upload

 public List<FileModel> Files { get; set; }
        public string Name { get; set; }
        public string Extension { get; set; }
        public string Description { get; set; }
        public string Author { get; set; }
        public string Year { get; set; }
        public string FilePath { get; set; }
        public string PublishedOn { get; set; }
        public int DownloadCounter { get; set; }
        public Genres Genre { get; set;}
        public int FileTypeId { get; set; }
        public List<SelectListItem> FtypeList { get; set; }
        public FileType FileT { get; set; }

I generate dropdown list to pick FileType with this code :

 public  IActionResult Index()
        {
            var vm = new FileUploadViewModel();
            vm.FtypeList = context.FileTypes
                .Select(a => new SelectListItem()
            {
                Value = a.Id.ToString(),
                Text=a.FileTypeName
            }).ToList();

            ViewBag.Message = TempData["Message"];
            return View(vm);
        }

And in view i have this

<div class="form-group row">
        <label asp-for="FileT" class="col-sm-2 col-form-label"> </label>
        <div class="col-sm-10">
            <select asp-for="FileT" class="custom-select mr-sm-2" asp-items="@Model.FtypeList"></select>
        </div>
        </div>

In the HttpPost action i do this

[HttpPost]
        public async Task<IActionResult> Index(List<IFormFile> files, string description,DateTime PublishedOn,string Author,string Name,FileType Ftype)
        {
            foreach (var file in files)
            {
                var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\Files\");
                bool basePathExists = System.IO.Directory.Exists(basePath);
                if (!basePathExists) Directory.CreateDirectory(basePath);
                var fileName = Path.GetFileNameWithoutExtension(file.FileName);
                var filePath = Path.Combine(basePath, file.FileName);
                var extension = Path.GetExtension(file.FileName);
               
                DateTime dateTime = DateTime.UtcNow;
                var createdOn = dateTime.ToShortDateString();
                if (!System.IO.File.Exists(filePath))
                {
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                    var fileModel = new FileModel
                    {
                        Year =createdOn,
                        PublishedOn = PublishedOn.ToShortDateString(),
                        FileType = file.ContentType,
                        Extension = extension,
                        Name = Name,
                        Description = description,
                        FilePath = filePath,
                        Author=Author,
                        Ftype=Ftype,
                    };
                    context.Files.Add(fileModel);
                    context.SaveChanges();
                }
            }
            TempData["Message"] = "File successfully uploaded to File System.";
            return RedirectToAction("Index","Home");
        } 

But when i upload file it doesnt get the selected value from dropdown list it create new item in the selected list.For example i have only 4 FileTypes in table if i select item with value=3 when file is uploaded to db in the table with uploaded files Ftype = 5 and it create new row in FileTypes table with Id = 5.

2

Answers


  1. fix your view, You have to use FileTypeId for select

     <select asp-for="FileTypeId" class="custom-select mr-sm-2" asp-items="@Model.FtypeList"></select
    ......
    
    

    and since you are using post your action input parameter should be the same as model

     public async Task<IActionResult> Index(FileModel viewModel)
       ......
    
    
    Login or Signup to reply.
  2. According to your FileUploadViewModel view model, I assume the FileTypeId is the user selected file type id value, right?

    If that is the case, I suggest you could modify your code as below:

    <div class="form-group row">
        <label asp-for="FileTypeId" class="col-sm-2 col-form-label"> </label>
        <div class="col-sm-10">
            <select asp-for="FileTypeId" class="custom-select mr-sm-2" asp-items="@Model.FtypeList"></select>
        </div>
    </div>
    

    Then, in the action method add the FileTypeId parameter, like this:

    [HttpPost]
    public async Task<IActionResult> CreateFile(List<IFormFile> files, string description, DateTime PublishedOn, string Author, string Name, FileType Ftype, int FileTypeId)
    {
    

    Then, when you create FileModel, you could check if the FileType exists or not based on the FileTypeId paramter. Check the following code:

    var fileModel = new FileModel
    {
        Year =createdOn,
        PublishedOn = PublishedOn.ToShortDateString(),
        FileType = file.ContentType,
        Extension = extension,
        Name = Name,
        Description = description,
        FilePath = filePath,
        Author=Author, 
    };
    
    //Check if the FileType exists or not, if exists, get the existing FileType and assign it to the new fileModel. if not exists, create a new FileType Model and assign it to the new fileModel.
    var filetype = context.FileTypes.Where(c => c.Id == FileTypeId).FirstOrDefault() 
    if (filetype!= null)
    {
        fileModel.Ftype = filetype; //using the existing file type.
    }
    else
    {
        var newFileType = new FileType();
        fileModel.Ftype = newFileType ; //using the new file type.
    }
    context.Files.Add(fileModel);
    context.SaveChanges();
    
    FileType = file.ContentType,
    

    Besides, it seems that the FileModel also contains the FileType, not sure the issue relate it or not, if you are using the Ftype property to set the file type, perhaps there is no need to set the FileType property.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search