Ajax.BeginForm向控制器发送参数

4

我在视图页面上有以下的Ajax.BeginForm

using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = @ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"}))
{
    @Html.AntiForgeryToken()
    <input type="file" name="files">   <input type="submit" value="Upload File to Server">
}

然后我有下面这个控制器方法在 FileUpload 控制器类中:

[HttpPost]
public ActionResult Financing_Product_Feature_Upload(HttpPostedFileBase file, string productid)
{

但是一旦我点击提交按钮,它就没有指向Financing_Product_Feature_Upload控制器方法。


3
尝试将参数HttpPostedFileBase file重命名为HttpPostedFileBase files,以便与输入标签的名称匹配。 - Massimo Franciosa
注意事项:您不能使用Ajax.BeginForm()上传文件,因此即使您更正了拼写错误,您的控制器也永远不会收到任何文件。 - user3559349
3个回答

3

MVC序列化处理基于名称属性。表单控件的名称需要与MVC控制器操作参数相匹配。在您的情况下,当您点击“提交”按钮时,浏览器控制台应该会显示错误消息,指出“在FileUpload控制器中找不到匹配的操作”,或者类似这样的意思。

@using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = @ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <input type="file" name="files">   <input type="submit" value="Upload File to Server">
}

public class FileUploadController : Controller
{
    [HttpPost]
    public ActionResult Financing_Product_Feature_Upload(HttpPostedFileBase  files, string productid)
    { 
        // Action code goes here
    }
}

2
尝试在 enctype 中添加 @。
using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = @ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { @enctype = "multipart/form-data"}))
                        {
                            @Html.AntiForgeryToken()
                            <input type="file" name="file">   <input type="submit" value="Upload File to Server">
                        }

0

在使用之前添加@

@using (Ajax.BeginForm("Financing_Product_Feature_Upload", "FileUpload", new { productid = ViewBag.Product_ID }, new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"}))
                        {
                            @Html.AntiForgeryToken()
                            <input type="file" name="files">   <input type="submit" value="Upload File to Server">
                        }

HttpPostedFileBase file 重命名为 files,因为这是您的文件输入名称。

一旦我在using前面添加了@字符,就会出现“Unexpected 'using' keyword after '@' character.”的错误。但是,在代码内部,您不需要使用“@”前缀来构造像“using”这样的语句。 - kez
@kez,你在其他代码块中使用了using,并且在那里使用了@。例如:@if(cond){ using(your).... 这就是你异常的原因,所以你不需要在using前加上@。 - TotPeRo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接