I have a form upload that works but I would like to pass model information for my database to save the file with a different name of course.
Here is my Razor view:
@model CertispecWeb.Models.Container
@{
ViewBag.Title = "AddDocuments";
}
<h2>AddDocuments</h2>
@Model.ContainerNo
@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<input type='file' name='file' id='file' />
<input type="submit" value="submit" />
}
Here is my Controller:
[HttpPost]
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"),
containers.ContainerNo);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
The model information is not passed through to the controller. I have read that I might need to update the model, how would I do this ?
If you won't always have images posting to your action, you can do something like this:
Your form doesn't contain any input tag other than the file so in your controller action you cannot expect to get anything else than the uploaded file (that's all that's being sent to the server). One way to achieve this would be to include a hidden tag containing the id of the model which will allow you to retrieve it from your datastore inside the controller action you are posting to (use this if the user is not supposed to modify the model but simply attach a file):
and then in your controller action:
On the other hand if you wanted to allow the user to modify this model then you will need to include the proper input fields for each field of your model that you want to be sent to the server:
and then you will have the default model binder reconstruct this model from the request:
For multiple files; note the newer "multiple" attribute for input:
Form:
Controller:
1st download jquery.form.js file from below url
http://plugins.jquery.com/form/
Write below code in cshtml
Action method :-
Solved
Model
Controller
And View
Note title of parameter from controller action must match with name of input elements
IEnumerable<HttpPostedFileBase> fileUpload
->name="fileUpload[0]"
fileUpload
must match