0

I have been working with MVC for the past few days.

I have a problem in one of my pages, i.e I have a page where q user enters the required details and uploads a file. I have two buttons named Upload for Uploading File and Create for creating new profile.

My Problem

My problem is I don't want to reload the whole page when user clicks on upload button. I was thinking of using an webmethod for fileupload.

I don't know if what am I doing wrong here

Can any one correct me

This is my Webmethod in my controller named Create

Controller

   [WebMethod]
   public string  FileUpload(HttpPostedFileBase file, BugModel model)
   {             
       BugModel bug = null;
       if (file != null && file.ContentLength > 0)
       {
           string path = "/Content/UploadedFiles/" + Path.GetFileName(file.FileName);
           string savedFileName = Path.Combine(System.Web.HttpContext.Current.Server.MapPath ("~" +path));
           file.SaveAs(savedFileName);
           BugAttachment attachment = new BugAttachment();
           attachment.FileName = "~" + path.ToString();
           bug.ListFile.Add(attachment);
           model = bug;              
       }
       return "FileUploaded";          
   }

used a script to call the method

Javascript

       <script type="text/javascript">
      function UploadFile() {       
        $.ajax({
            type:"Post",
            url: "LogABug/FileUpload",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                alert("File Uploaded")
            },
            error: function () {
                ErrorMessage("Try Again");
            }
        });
    }
 </script>

can any one tell me how can I do this ...if this is the wrong method correct me the right one with the ideas please

Paul George
  • 1,788
  • 16
  • 33
SoftwareNerd
  • 1,875
  • 8
  • 29
  • 58

1 Answers1

0

You are uploading the file separately. Therefore you will need two actions:

  • public string Something(BugModel model) for the model.
  • public string FileUpload(HttpPostedFileBase file) for the file

Now, I would use jQuery Form Plugin for ajax submitting. Here is an example:

<script type="text/javascript">
    $(function () {
        $("#file-upload-form").submit(function () {
            $(this).ajaxSubmit({
                target: "#message",
                cache: false
            });

            return false;
        });
    });
</script>
@using(Html.BeginForm("FileUpload", "LogABug", FormMethod.Post, new { enctype = "multipart/form-data", id = "file-upload-form" })) {
    @Html.ValidationSummary(true)
    <fieldset>
        @Html.EditorFor(model => model.File)
        <input type="submit" value="Upload" />
    </fieldset>
}
<div id="message">
</div>

What ever you return from your action will be displayed in the div with id message

Mohayemin
  • 3,841
  • 4
  • 25
  • 54