Problem with updating model with attachments using ajax and mvc

I have the code below. I am trying to update the table when an attachment is being add and/or deleted.  The table is in a partial view.  The issue is that my model.Attachments is not being updated when I go to submit the entire request.  The table displays the row but the model isn't being updated with the new data.  What am I doing wrong?

<div class="form-group row">
                <div class="col-sm-6">
                    @Html.EditorFor(model => model.AttachmentsJSON, new { htmlAttributes = new { @class = "form-control" } })
                    <table class="table" id="ListofFiles">
                        <thead>
                            <tr>
                                <th>Filename</th>
                                <th>Attachment Type</th>
                                <th>Description</th>
                            </tr>
                        </thead>
                        <tbody>
                            @if (Model.Attachments.Count() != 0)
                            {
                                var idCount = 0;

                                foreach (var item in Model.Attachments)
                                {
                                    idCount = idCount + 1;
                                    <tr id="@idCount">
                                        <td>@item.Filename</td>
                                        <td>@item.AttachmentType.Type</td>
                                        <td>@item.Description</td>
                                        <td><a href="#" class="btn btn-danger" onclick="ShowDeleteModal(@item.ID)"><i class="glyphicon glyphicon-trash"></i> </a> </td>
                                    </tr>
                                }
                            }
                            else
                            {
                                <tr>
                                    <td colspan="4" align="center">
                                        There are no attachments
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            </div>

Open in new window


function AddAttachment() {
    var data = new FormData();

    var files = $("#attachmentUpload").get(0).files;

    var typeId = $("#attachmentTypeId :selected").val();
    var attachmentType = $("#attachmentTypeId :selected").text();
    var description = $("#description").val();
    //var attachmentsByRequest = JSON.parse($("#attachmentJSONModal").val());

    
    data.append("AttachmentTypeId", typeId);
    data.append("AttachmentType", attachmentType);
    data.append("AttachmentUpload", files[0]);
    data.append("Description", description);
    data.append("Filename", files[0].name);
   // data.append("AttachmentsJSON", JSON.stringify(attachmentsByRequest));

    $.ajax({
        url: '/Request/UploadFile',
        type: "POST",
        contentType: false, // Not to set any content header
        processData: false, // Not to process data
        data: data,
        async: false,
        success: function (result) {
            $("#attachmentModal").modal("hide");
            if (result != "") {        
                
                $('#addAttachmentBtn').find("*").prop("disabled", true);
                //LoadProgressBar(result); //calling LoadProgressBar function to load the progress bar.
                var markup = "<tr><td>" + result.Filename + "</td><td>" + result.AttachmentType + "</td><td>" + result.Description + "</td><td><a href='#' class='btn btn-danger' onclick='DeleteFile(\"" + result + "\")'><i class='glyphicon glyphicon-trash'></i></a></td></tr>"; // Binding the file name
                $("#ListofFiles tbody").append(markup);
                $('#addAttachmentBtn').find("*").prop("disabled", false);
            }
        },
        error: function (err) {
            alert(err.statusText);
        }
    });
};

Open in new window

Natavia FinnieSenior Analyst Technical Focus ApplicationsAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
you should  describe your issue...
it look like you think your table will be updated automatically after using ajax
currently I see you mix two logics
1 - ajax
supposed to allow sending data WITHOUT refreshing the page
if you decide to use ajax, you should handle the refreshing part

2 - and the first page seems to be able to display the files sent but we don't see how it should refresh
maybe this first part is your Request/UploadFile "page"?
0
Natavia FinnieSenior Analyst Technical Focus ApplicationsAuthor Commented:
@leakim971,
 Thank you. I was moving so fast. I just updated with issue:
The table is in a partial view.  The issue is that my model.Attachments is not being updated when I go to submit the entire request.  The table displays the row but the model isn't being updated with the new data.  What am I doing wrong?
0
leakim971PluritechnicianCommented:
what is the code of /Request/UploadFile ?
0
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Natavia FinnieSenior Analyst Technical Focus ApplicationsAuthor Commented:
@leakim971

 [HttpPost]
        public ActionResult UploadFile(AttachmentViewModel attachment)
        {
       
            string FileName = "";
            HttpFileCollectionBase files = Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "Attachments/";              

                HttpPostedFileBase file = files[i];
                string fname;

                // Checking for Internet Explorer    
                if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                {
                    string[] testfiles = file.FileName.Split(new char[] { '\\' });
                    fname = testfiles[testfiles.Length - 1];
                }
                else
                {
                    fname = file.FileName;
                    attachment = new AttachmentViewModel()
                    {
                        Description = attachment.Description,
                        Filename = attachment.Filename,
                        AttachmentTypeId = attachment.AttachmentTypeId,
                        AttachmentType = attachment.AttachmentType,
                        AttachmentsJSON = JsonConvert.SerializeObject(attachment.AttachmentsJSON)
                    };
                    
                    FileName = file.FileName;                    
                }

                // Get the complete folder path and store the file inside it.    
                fname = Path.Combine(Server.MapPath("~/Attachments/"), fname);
                file.SaveAs(fname);
            }
            return Json(attachment, JsonRequestBehavior.AllowGet);
        }

Open in new window

0
Natavia FinnieSenior Analyst Technical Focus ApplicationsAuthor Commented:
@leakim971
The table is on a partial view name "_Attachments"
0
leakim971PluritechnicianCommented:
ok, for you, why the partialview should refresh/update?
you should return the partial view instead a JSON object and update the page with the "success" Ajax method
0
Natavia FinnieSenior Analyst Technical Focus ApplicationsAuthor Commented:
@leakim971,
How is that done and keeping the partial in the same place? I tried it before and once it returned as it's own individual page and then with another try I got a crazy error
0
leakim971PluritechnicianCommented:
instead :
return Json(...
you should have :
return PartialView(...

and :
    $.ajax({
        url: '/Request/UploadFile',
        type: "POST",
        contentType: false, // Not to set any content header
        processData: false, // Not to process data
        data: data,
        async: false,
        success: function (partialView) {
               $(".emplacementToDisplayYouPartialView").html( partialView ); 

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Natavia FinnieSenior Analyst Technical Focus ApplicationsAuthor Commented:
@leakim971 is awesome and very thorough!!!! Thank you
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.