ASP.NET MVC - How to call void controller method without leaving the view?

前端 未结 7 2284
北恋
北恋 2020-12-01 11:51

Question background:

I am implementing some basic \'shopping cart\' logic to an MVC app. Currently when I click a link - denoted as \'Add T

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 12:46

    As many people mentioned here you will need to use AJAX if your using asp.net MVC to hit a controller POST function without having to leave your view.

    A good use case for this is if you want to upload a file without refreshing the page and save that on the server.

    All of the

    return new EmptyResult();
    

    Wont work, they will still redirect you.

    Here is how you do it, in your view have the follow form as an example:

                

    The CSV you want to upload:

    Then in the JavaScript side you need to add this to your view with within Script tags.

      $("#my-form").on('submit', function (event) {
            event.preventDefault();
            // create form data
            var formData = new FormData();
            //grab the file that was provided by the user
            var file = $('.file-upload')[0].files[0];
            // Loop through each of the selected files.
            formData.append('file', file);
            if (file) {
                // Perform the ajax post
                $.ajax({
                    url: '/YourController/UploadCsv',
                    data: formData,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (data) {
                        alert(data);
                    }
                });
            }
        });
    

    Your controller might look something like this to process this type of file:

        [HttpPost]
        public void UploadCsv()
        {
            var listOfObjects = new List();
            var FileUpload = Request.Files[0]; //Uploaded file
            //check we have a file
            if (FileUpload.ContentLength > 0)
            {
                //Workout our file path
                string fileName = Path.GetFileName(FileUpload.FileName);
                string path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
    
                //Try and upload
                try
                {
                    //save the file
                    FileUpload.SaveAs(path);
    
                    var sr = new StreamReader(FileUpload.InputStream);
                    string csvData = sr.ReadToEnd();
    
                    foreach (string r in csvData.Split('\n').Skip(1))
                    {
                        var row = r;
                        if (!string.IsNullOrEmpty(row))
                        {
                            //do something with your data
                            var dataArray = row.Split(',');
                        }
                    }
    
    
                }
                catch (Exception ex)
                {
                    //Catch errors
                    //log an error
                }
            }
            else
            {
                //log an error
            }
        }
    

提交回复
热议问题