Search code examples
c#jqueryasp.net-mvcdashboard

How to execute an action from a partial view using ASP.Net MVC?


I have a problem executing an action from a partial view that is used inside another view.

I've tried this JQuery used to change the content of the div

$(document).ready(function () {
        //File Upload Button
        $(".fileUpload").click(function () {
            $.ajax({

                type: 'GET',
                url: '@Url.Action("FileUpload", "Dashboard")',
                data: { type: $(this).attr("data-type") },
                success: function (response) {
                    $(".content").html(response);
                },
                error: function () {
                    alert("Problem on uploading file");
                }

            });

        });
    });

And this the code under the controller to load the partial view.

public ActionResult FileUpload()
{
  return PartialView("~/Views/Dashboard/FileUpload.cshtml");
}

I've managed to run this code and show the partial view but I'm having a hard time now how to execute the action from that partial view.

I've added another action Fileload

[HttpPost]
public ActionResult FileLoad()
        {
             //some codes to execute
        }

That will be called by this partial view

@model Payout.Models.FundTransfer

@using (Html.BeginForm("FileLoad", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        <input type="file" name="Filepath" id="Filepath" />
    </div>
        <div>
            <input type="submit" name="submit" value="Submit" />
        </div>
}

And now I don't know what is the best way to execute that action. Do you have any suggestions?


Solution

  • Could you modify your code as below

    $.ajax({
              url: '@Url.Action("FileUpload", "Dashboard")',
              type: "POST",
              processData: false,
              data: { type: $(this).attr("data-type") },
              dataType: "html",
              contentType: false,
              success: function (data) {
                  $(".content").html(response);
              },
              error: function () {
                  alert("Problem on uploading file");
              }
          });