Reputation: 168
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 :
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?
Upvotes: 0
Views: 123
Reputation: 48415
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:
@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:
document.forms[0].submit();//assuming you only have one form
Also, your action parameters don't seem to match anything. Specifically ShopID
and products
. You will probably get an error because you don't have default values for them. I am not 100% sure on that part though. Or maybe you have then in other parts of your form, so it might be ok
Upvotes: 1