Per*_*an. 41 .net c# asp.net-mvc razor asp.net-mvc-3
我有一个上传表单,我想传递我的信息,如图像和其他一些领域,但我不知道如何上传图像..
这是我的控制器代码:
[HttpPost]
public ActionResult Create(tblPortfolio tblportfolio)
{
if (ModelState.IsValid)
{
db.tblPortfolios.AddObject(tblportfolio);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tblportfolio);
}
Run Code Online (Sandbox Code Playgroud)
这是我的查看代码:
@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>
}
Run Code Online (Sandbox Code Playgroud)
现在我不知道如何上传图像并将其保存在服务器上..如何设置图像名称Guid.NewGuid();
?或者我该如何设置图像路径?
mat*_*mmo 45
首先,您需要更改视图以包含以下内容:
<input type="file" name="file" />
Run Code Online (Sandbox Code Playgroud)
然后,你需要改变你的职位ActionMethod
采取了HttpPostedFileBase
,就像这样:
[HttpPost]
public ActionResult Create(tblPortfolio tblportfolio, HttpPostedFileBase file)
{
//you can put your existing save code here
if (file != null && file.ContentLength > 0)
{
//do whatever you want with the file
}
}
Run Code Online (Sandbox Code Playgroud)