Problem with updating model with attachments using ajax and mvc

Natavia Finnie
Natavia Finnie used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
leakim971Multitechnician
Top Expert 2014

Commented:
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"?
Natavia FinnieSenior Analyst Technical Focus Applications

Author

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?
leakim971Multitechnician
Top Expert 2014

Commented:
what is the code of /Request/UploadFile ?
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Natavia FinnieSenior Analyst Technical Focus Applications

Author

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

Natavia FinnieSenior Analyst Technical Focus Applications

Author

Commented:
@leakim971
The table is on a partial view name "_Attachments"
leakim971Multitechnician
Top Expert 2014

Commented:
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
Natavia FinnieSenior Analyst Technical Focus Applications

Author

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
Multitechnician
Top Expert 2014
Commented:
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

Natavia FinnieSenior Analyst Technical Focus Applications

Author

Commented:
@leakim971 is awesome and very thorough!!!! Thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial