Handling 2 buttons submit Actions in a single View/Form - ASP.NET MVC 2 RTM

人盡茶涼 提交于 2019-12-19 04:07:13

问题


I have a View in which the user is able to upload a file to the server.

In this view I also have 2 buttons: one to Upload a file and other to Download the last file imported.

In my Controller I created 2 action methods: Import and Export.

How could I manage to redirect each button click to the proper action method in my Controller?

I have tried Html.ActionLink:

<%= Html.ActionLink("Upload", "Import", "OracleFile")%>
<%= Html.ActionLink("Download", "Export", "OracleFile")%>

Html.ActionLink didn't do the trick. The action links were taking me to the right Action methods but they were generating a GET request. This way Request.Files.Count = 0.

I need a POST request.

Note: the most intriguing part is that the upload was working and all of sudden it stopped working. I've seen that some people are having the same problem with FileUpload tasks in which the Request.Files is always Empty. I think it's empty because you need a post to the server. Isn't it?


回答1:


maybe this will give u the idea:

view:

<form enctype="multipart/form-data" method="post" action="/Media/Upload/Photo">
    <input type="file" name="file" id="file" /> 
    <input type="submit"  name= "submitImport" value="Upload" />
    <input type="submit" name = "submitExport"  value="Download" />
</form>

controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Action (FormCollection formCollection)
        {
            if (formCollection["submitImport"] != null)
            {
                return Import(formCollection);
            }
             if (formCollection["submitExport"] != null)
            {
                return Export(formCollection);
            }
        }

the Export and Import are the appropriateactions




回答2:


You have to use a "multipart/form-data" form, and submit the form. No ActionLink.

<form enctype="multipart/form-data" method="post" action="/Media/Upload/Photo">
    <input type="file" name="file" id="file" /> 
    <input type="submit" value="Upload" />
</form>



回答3:


To generate a POST request for the upload, use the File Input form element and just post back to the server ala normal.

http://www.w3schools.com/jsref/dom_obj_fileupload.asp

Have a look at this blog post from Scott Hanselman. http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx



来源:https://stackoverflow.com/questions/2444245/handling-2-buttons-submit-actions-in-a-single-view-form-asp-net-mvc-2-rtm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!