簡體   English   中英

如何在不使用JS FormData的情況下將文件上傳到ASP.NET MVC控制器操作

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

我有一個端點

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

        // ... 

        return this.View(model); 
   }

它將model傳遞到名為Create.cshtml視圖中,並從另一個具有

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

問題是我想要另一個可以擊中相同端點並上傳文件的按鈕。 我有

<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>

它成功上傳了文件,但是隨后return this.View(model)僅返回響應中的視圖,但不能導航到頁面。 我嘗試創建一個不同的端點並執行此操作this.RedirectToAction("Create", new { projectId = projectId })但是發生了相同的問題。 知道我在使用AJAX / jQuery並上傳文件時實際上如何才能將我的/Create頁面導航到嗎?或者還有其他方法嗎?

我想你需要這樣

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

您可以查看一些證明該想法的鏈接http://ajeeshms.in/articles/upload-files-using-ajax-in-asp-net-mvc/ https://forums.asp.net/t/2024764.aspx將+表單+數據+傳遞給+控制器+方法+使用+ Ajax

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM