简体   繁体   English

将文件从View发布到Controller

[英]Post a file from View to Controller

I have following code in view : 我有以下代码:

<div>
  <input type="file" name ="file" onchange="location.href='<%: Url.Action("ChangeImage", new{Id = Model.Id}) %>'" />
</div>

And in Controller I have the ChangeImage method : 在Controller中,我具有ChangeImage方法:

  public ActionResult ChangeImage(FormCollection collection, int Id,Products products)
    {
        var file = Request.Files["file"];

        //Do something
    }

But the selected file does not post to the controller. 但是所选文件不会发布到控制器。 What is the problem? 问题是什么? How can I send the file content to the controller to use it? 如何将文件内容发送到控制器以使用它?

Because you are not posting the form data is probably the reason. 因为您未发布表单数据,可能是原因。

When creating an MVC form for submitting files you must specify the "enctype", with the helpers you can do this: 在创建用于提交文件的MVC表单时,您必须指定“ enctype”,并借助助手可以执行以下操作:

@using (Html.BeginForm("MyAction", "MyController", new { @Id = Model.Id }, FormMethod.Post, new { name = "Form", enctype = "multipart/form-data" }))
{
    //all form fields code in here
}

Then you will want to change your javascript to post the form, something like: 然后,您将需要更改JavaScript以发布表单,例如:

document.forms[0].submit();//assuming you only have one form

Also, your action parameters don't seem to match anything. 另外,您的操作参数似乎不匹配任何内容。 Specifically ShopID and products . 特别是ShopIDproducts You will probably get an error because you don't have default values for them. 您可能会得到一个错误,因为您没有默认值。 I am not 100% sure on that part though. 不过,我对那部分并不确定100%。 Or maybe you have then in other parts of your form, so it might be ok 或者也许您随后在表单的其他部分,所以可能没问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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