Click here to Skip to main content
15,886,664 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello dear all,

I have to create form with upload file function. I use .NET framework asp.net mvc5 and C# as a language. but I couldn't find tutorial for my form. I tried my best and I really need help of you guys. I'm going to add my model, view and controller here.

Please help for solve my problem. Thank you

What I have tried:

Model

<pre>using System.Collections.Generic;

namespace PMSWebApplication.Models.DomainModels
{
    public class Attachment
    {
        public Attachment()
        {
            BugFixes = new HashSet<BugFix>();
            Updates = new HashSet<Update>();
        }
        public int Id { get; set; }
        public int ProjectId { get; set; }
        public Project Project { get; set; }
        public string UserId { get; set; }
        public ApplicationUser User { get; set; }
        public string FileName { get; set; }
        public string UploadFile { get; set; }
        //public string Type { get; set; }
        public string Description { get; set; }

        public virtual ICollection<BugFix> BugFixes { get; set; }
        public virtual ICollection<Update> Updates { get; set; }


    }
}


Controller

<pre>using System.Data.Entity;
using System.Threading.Tasks;
using System.Net;
using System.Web.Mvc;
using PMSWebApplication.Models;
using PMSWebApplication.Models.DomainModels;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;

namespace PMSWebApplication.Controllers
{
    public class AttachmentsController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Attachments
        public async Task<ActionResult> Index(/*HttpPostedFileBase file*/)
        {
           
            var attachments = db.Attachments.Include(a => a.Project).Include(a => a.User);
            return View(await attachments.ToListAsync());
        }


        // GET: Attachments/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Attachment attachment = await db.Attachments.FindAsync(id);
            if (attachment == null)
            {
                return HttpNotFound();
            }
            return View(attachment);
        }

        // GET: Attachments/Create
        public ActionResult Create()
        {

            var users = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)).Users;

            ViewBag.ProjectId = new SelectList(db.Projects, "Id", "ProjectName");
            ViewBag.UserId = new SelectList(users, "Id", "Email");
            return View();
        }

        // POST: Attachments/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "Id,ProjectId,UserId,FileName,UploadFile,Type,Description")] Attachment attachment)
        {
            if (ModelState.IsValid)
            {
                db.Attachments.Add(attachment);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            var users = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)).Users;

            ViewBag.ProjectId = new SelectList(db.Projects, "Id", "ProjectName", attachment.ProjectId);
            ViewBag.UserId = new SelectList(users, "Id", "Email", attachment.UserId);
            return View(attachment);
        }

        // GET: Attachments/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Attachment attachment = await db.Attachments.FindAsync(id);
            if (attachment == null)
            {
                return HttpNotFound();
            }

            var users = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db)).Users;

            ViewBag.ProjectId = new SelectList(db.Projects, "Id", "ProjectName", attachment.ProjectId);
            ViewBag.UserId = new SelectList(users, "Id", "Email", attachment.UserId);
            return View(attachment);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}



View

index

@model IEnumerable<PMSWebApplication.Models.DomainModels.Attachment>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Attachments</h2>

@*@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,new { enctype="multipart/form-data"}))
{
    <input type="file" name="file" />
    <br/>*@
    @*<input type="submit" value="Upload" class="btn btn-primary" />*@

@*}*@

<p>
    @Html.ActionLink("Create New Attachment", "Create", null, new { @class = "btn btn-info" })
</p>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Project.ProjectName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.User.UserLevel)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FileName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FileType)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Type)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Project.ProjectName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.User.UserLevel)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FileName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FileType)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Type)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Description)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "btn btn-primary btn-sm" }) |
            @Html.ActionLink("Details", "Details", new { id = item.Id }, new { @class = "btn btn-info btn-sm" }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @class = "btn btn-warning btn-sm" })
        </td>
    </tr>
}

</table>


create

@model PMSWebApplication.Models.DomainModels.Attachment

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    

    <div class="form-horizontal">
        <h4>Attachment</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.ProjectId, "ProjectId", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("ProjectId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ProjectId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.UserId, "UserId", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("UserId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FileName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FileType, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FileType, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FileType, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Type, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Type, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Type, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Posted
Updated 23-May-21 22:32pm
v4
Comments
SeanChupas 14-May-21 12:22pm    
Where is your upload code? You need to click Improve Question and clear out all of the non relevant code. It's too much code to look through. There's no reason to post your Delete method, for example. Clean it up so we can see it easier.

1 solution

You can't send a file name or path from the client to the server - the code running on the server doesn't have access to the files on the client.

Instead, you need to use a file input:
<input type="file"> - HTML: HyperText Markup Language | MDN[^]

In your model, this will be represented as a HttpPostedFileBase property.
C#
public class Attachment
{
    ...
    public HttpPostedFileBase UploadFile { get; set; }
    ...

You will need to ensure that the containing <form> has enctype="multipart/form-data".
Razor
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype="multipart/form-data" })) 
{
    ...
    <div class="form-group">
        @Html.LabelFor(model => model.UploadFile, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UploadFile, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.UploadFile, "", new { @class = "text-danger" })
        </div>
    </div>
    ...
Your controller will need to save the file somewhere on the server's file system, and then save that path in the database.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900