skip to Main Content

I want to send txt file to action and get text words count without submiting form.

my codes in action works well (this action get HttpPostedFileBase and using with stream reader return count)so problem is in View.

this is My Code in View to send file to view and get result:

<script>

    $("#MyForm").submit(function (event) {
        event.preventDefault();

        var files = $('#fileInput').files[0]);

        $.ajax({
            type: "Post",
            url: "/Counter/GetCount",
            enctype: "multipart/form-data",
            data: files
        }).done(function (result) {

            $("#result").html(result);

        });
</script>

if you can, fix my code or give me new code i want to see your suggestions for doing this.

Edit code from comment:

[HttpPost] 
public ActionResult GetCount(HttpPostedFileBase file) 
{ 
  using (StreamReader reader = new StreamReader(file.FileName)) 
  { 
    string result = reader.ReadToEnd(); 
    return PartialView(result.Count()); 
  } 
}

2

Answers


  1. You can try to replace ajax request code with:

    $.ajax({
      url: "/Counter/GetCount",
      data:files,
      type:'POST',
      contentType: false,
      processData: false,
      success: function(result){
        $("#result").html(result);
      }
    });
    
    Login or Signup to reply.
  2. You can try to use FormData to pass files to action with ajax.Here is a working demo:

    view:

    <form id="MyForm" method="post">
        <input id="fileInput" type="file" />
        <input type="submit" value="submit"/>
    </form>
    <script>
            $("#MyForm").submit(function (event) {
                event.preventDefault();
                var formData = new FormData();
                formData.append('file', $('#fileInput').get(0).files[0]);
                $.ajax({
                    type: "Post",
                    url: "/Counter/GetCount",
                    data: formData,
                    processData: false,
                    contentType: false,
                }).done(function (result) {
    
                    $("#result").html(result);
    
                });
            })
        </script>
    

    Action:

    [HttpPost] 
    public ActionResult GetCount(IFormFile file) 
    { 
      using (StreamReader reader = new StreamReader(file.FileName)) 
      { 
        string result = reader.ReadToEnd(); 
        return PartialView(result.Count()); 
      } 
    }
    

    Result:
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search