実際、私は MVC の初心者で、ニュース ページの作成を開始しました。このページタイトルでは、ニュースの本文とその写真ルートはDBに保存されますが、写真はサーバーフォルダに保存されます。だから私はDBのモデルを作成しました:
public class NewsEntry
{
public int Id { get; set; }
[Required(ErrorMessage = "Please enter a suitable title for your news")]
public string title { get; set; }
[Required(ErrorMessage = "Please enter the body news")]
public string body { get; set; }
public string image { get; set; }
public DateTime dateAdded { get; set; }
}
そして写真の別のモデル:
public class UploadImageViewModel
{
public string Photo { get; set; }
public HttpPostedFileBase PhotoUpload { get; set; }
}
その後、コントローラーで次のようなアクションを作成しました。
private UploadImageViewModel model = new UploadImageViewModel();
[HttpPost]
public ActionResult Create(NewsEntry entry)
{
string uploadPath = "~/images/NewsImages";
var file = model.PhotoUpload;
if (model.PhotoUpload.ContentLength > 0)
{
var fileName = Path.GetFileName(model.PhotoUpload.FileName);
var path = Path.Combine(Server.MapPath(uploadPath), fileName);
model.PhotoUpload.SaveAs(path);
model.Photo = uploadPath + fileName;
entry.image = model.Photo;
}
var profile = AutoMapper.Mapper.Map<NewsEntry>(model);
var validTypes = new[] { "image/jpeg", "image/pjpeg", "image/png", "image/gif" };
if (!validTypes.Contains(model.PhotoUpload.ContentType))
{
ModelState.AddModelError("Photo Upload", "Please Upload either a JPG, GIF, or PNG image.");
}
if (ModelState.IsValid)
{
entry.dateAdded = DateTime.Now;
_db.Entries.Add(entry);
_db.SaveChanges();
}
return RedirectToAction("Index");
}
最後に、このアクションのビューを追加しました:
@Html.ValidationSummary()
@using(Html.BeginForm()) {
<p>Please enter your news title: </p>
@Html.TextBox("title")
<br /><br />
<p>Please enter your news body: </p>
@Html.TextArea("body",new{rows=10,cols=45})
<br /><br />
<p>Please enter the source of your news: </p>
@Html.TextBox("Source")
<br /><br />
<div class="editor-field">
<label for="PhotoUpload">Upload an image for your news </label>
@Html.TextBox("PhotoUpload", null, new { type="file" })
</div>
<br /><br />
<input type="submit" value="Submit the news" >
}
しかし、返信された写真はなく、AutoMapper にも問題があります。私は何をすべきか?誰かが私の問題を解決できるなら、私は感謝します。