smc develpments

smc develpments

  • NA
  • 121
  • 1.3k

Uploading attachments and details in to different database tables

Jun 18 2021 2:49 AM

I'm still new to this ASP.NET MVC and I started a small project. There I want to send the Request main details to one table and attachments into another table. Within the create the main view, I added a partial view for the attachment section.

Here is what my model looks like.

public class App_GeneralRequest
{
    [Key]
    public int Id { get; set; }

    [Required]
    [DisplayName("Select Company")]
    public int CompanyId { get; set; } 

    [Required]
    [DisplayName ("Requesting Date")]
    public DateTime? Req_Date { get; set; } = DateTime.Now;

    [Required]
    [DisplayName("Requesting By")]
    public int Req_User { get; set; }

    [Required]
    [DisplayName("Requesting Location")]
    public int Location { get; set; }

    [Required]
    [DisplayName("Request Heading")]
    [StringLength(200)]
    public string Req_Heading { get; set; }

    [Required]
    [DisplayName("Cover Note")]
    [StringLength(800)]
    public string Req_CoverNote { get; set; }

    public bool Req_Status { get; set; }

    public int CreateBy { get; set; }
    public DateTime? CreateDate { get; set; } = DateTime.Now;

    public IList<GeneralRequest_Items> RequestAttachments { get; set; }
    
    public App_GeneralRequest()
    {
        RequestAttachments = new List<GeneralRequest_Items>();
    }

     public virtual IList<GeneralRequest_Items> GeneralRequest_Items { get { return 
     RequestAttachments; } set { value = RequestAttachments; } }

}

public class GeneralRequest_Items
{  
    [Key]
    public int Id { get; set; }

    [Required] 
    [ForeignKey("App_GeneralRequest")]
    public int Req_Id { get; set; }
    public virtual App_GeneralRequest App_GeneralRequest { get; set; }

    [DisplayName("Attach Quotation")]
    public byte[] Attachment_Pdf { get; set; }
    public byte[] Attachment_Jpeg { get; set; }

    [DisplayName("Describe the Attachment")]
    public string Attach_Description { get; set; }

    [DisplayName("Attachment Value")]
    public decimal Attachment_Value { get; set; }
}

So my view goes like this.

@model Asp_PASMVC.Models.GeneralRequest_Items
@using Asp_PASMVC.Infrastructure
<li style="padding-bottom:15px">
    @using (Html.BeginCollectionItem("RequestAttachments"))
    {
        <div class="row">
            <div class="col-md-4">
                <div class="form-group">
                    @Html.LabelFor(model => model.Attachment_Jpeg, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        <input type="file" name="ImageData" id="ImageData" onchange="checkImage(this)" />
                        @Html.ValidationMessageFor(model => model.Attachment_Jpeg, "", new { @class = "text-danger" })
                    </div>
                </div>
                <img id="imageDisplay" src="" alt="" width="100" height="100" class="ml-1" />
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    Attachment Description
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Attach_Description, new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.Attach_Description, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    Attachment Value
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Attachment_Value, new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.Attachment_Value, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        </div>
        <a href="#" onclick="$(this).parent().remove();">Delete</a>
    }
</li>
<script>
    $('.js-dropdown').select2({
        width: '100%', // need to override the changed default

    });
</script>
<script type="text/javascript">

    function checkImage(obj) {
        var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];

        if ($.inArray($(obj).val().split('.').pop().toLowerCase(), fileExtension) == -1) {

            msgDisplay('error', 'Upload Error', 'Only .jpeg, .jpg, .png, .gif, .bmp formats are allowed.');
            $("#imageDisplay").prop('src', '');
        }
        else {
            var files = obj.files;
            var reader = new FileReader();
            name = obj.value;
            reader.onload = function (e) {

                $("#imageDisplay").prop('src', e.target.result);
            };
            reader.readAsDataURL(files[0]);
        }
    }
</script>

So my concern is, I can add data to the main view and as well as the partial view, (attachment details). There in the attachments user need to add an attachment and type the description, and the amount. So there can be one or more attachments.

When I press create. App_GeneralRequest data will pass to the table and the GeneralRequest_Items data passes without the attachments. So attachment field is null, but the description and amount fields are passing normally.

This is my App_GeneralRequestController

public ActionResult Create(App_GeneralRequest app_GeneralRequest)
{
    if (ModelState.IsValid)
    {
         HttpPostedFileBase file = Request.Files["ImageData"];              
         app_GeneralRequest.RequestAttachments = ConvertToBytes(file);
        user.Image = ConvertToBytes(file);

        app_GeneralRequest.CreateBy =int.Parse(((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("UserId").Value);
        app_GeneralRequest.CreateDate = DateTime.Now;

        db.App_GeneralRequest.Add(app_GeneralRequest);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(app_GeneralRequest);
}

public byte[] ConvertToBytes(HttpPostedFileBase image)
{
    byte[] imageBytes = null;
    BinaryReader reader = new BinaryReader(image.InputStream);
    imageBytes = reader.ReadBytes((int)image.ContentLength);
    return imageBytes;
}