简体   繁体   中英

How to upload a file to an ASP.NET MVC controller action without using JS FormData

I have an endpoint like

    public ActionResult Create(int? projectId = null)
    {
        if (!projectId.HasValue)
        {
            throw new ArgumentException(nameof(projectId));
        }

        // ... 

        return this.View(model); 
   }

which passes the model into a view called Create.cshtml and essentially renders that page when it is clicked from another view that has

<a href="@Url.Action("Create", new { projectId = ViewBag.ProjectId })" class="btn btn-link">
    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Project    </a>

The issue is that I want another button that can hit the same endpoint and upload a file. I have

<form id="branch-config">
    <input type="file" name="json" />
    <button type="submit" class="btn btn-link">
        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Project Using Config
    </button>
</form>
<script>
    $(document).ready(function () {
        //form Submit action
        $("#branch-config").submit(function (evt) {
            evt.preventDefault();
            var formData = new FormData($(this)[0]);
            $.ajax({
                url: "@Url.Action("Import", new { projectId = ViewBag.ProjectId })",
                type: 'GET',
                data: formData,
                async: true,
                cache: false,
                contentType: false,
                enctype: 'multipart/form-data',
                processData: false
            });
            return false;
        });
    });
</script>

which successfully uploads the file, but then return this.View(model) just returns the view in the response but does not navigate to the page, so to speak. I tried creating a different endpoint and doing this.RedirectToAction("Create", new { projectId = projectId }) but the same problem happened. Any idea how I can actually get my /Create page to be navigated to when using AJAX/jQuery and uploading a file, or is there another way altogether?

I think you need s.th like this

[HttpPost]
public JsonResult Create(int projectId)
{
    // your code here
}

You can review some links for proving that idea http://ajeeshms.in/articles/upload-files-using-ajax-in-asp-net-mvc/ https://forums.asp.net/t/2024764.aspx?Passing+form+data+to+a+controller+method+using+Ajax

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM