I have a Upload form and I want to pass my information such as an Image and some other field but I don't know how can I upload Image ..
this is my controller code :
[HttpPost]
public ActionResult Create(tblPortfolio tblportfolio)
{
if (ModelState.IsValid)
{
db.tblPortfolios.AddObject(tblportfolio);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tblportfolio);
}
And this is my view code :
@model MyApp.Models.tblPortfolio
<h2>Create</h2>
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>tblPortfolio</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ImageFile)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.ImageFile, new { type = "file" })
@Html.ValidationMessageFor(model => model.ImageFile)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Link)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Link)
@Html.ValidationMessageFor(model => model.Link)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Now I don't know how can I upload Image and save it on server .. how can I set Image name by Guid.NewGuid();
? Or how can I set Image Path ?
You can get it from
Request
usingRequest.Files
Collection, In case of single file upload just read from the first index usingRequest.Files[0]
:In case of Multiple files uploading, you have to iterate on the
Request.Files
collection:If you want to upload file without page refresh via ajax then you can use this article which uses jquery plugin
Firstly, you'll need to change your view to include the following:
Then you'll need to change your post
ActionMethod
to take aHttpPostedFileBase
, like so: