2017-10-25 12 views
0

私はASP.NET MVCを使用していますが、製品の編集フォームがあります。商品には編集可能な画像リンクがあります。ASP.NET MVCフォームを提出した後にファイルパスが空です

public class Product 
{ 
    public int ProductId{ get; set; } 
    public string ImgUrl{ get; set;} 
} 

形態:私は画像のURLを格納し、モデルのみがこのURLが含まれているDBで

@using (Html.BeginForm("EditProduct", "Products", FormMethod.Post)) 
{ 
    <img src="@Url.Content(Model.ImgUrl)" /> 
    @Html.TextBoxFor(m => m.ImgUrl, new { @type="file", @id="file-upload" }) 
    <input type="submit" class="btn btn-primary" /> 
} 

また私が空であるアクションメソッドを持っています瞬時:

[HttpPost] 
    public ActionResult EditProduct(Product product) 
    { 
     return View(); 
    } 

2つの問題があります。

まず、product.ImgUrlのフォームを送信した後は、nullです。

#file-uploadの値は、ファイルの選択後も変更されません。

+0

たぶん私は間違っているが、あなたのクラスを見て、あなたはあなたのImgUrl文字列のための「セット」のトンを忘れてしまいました。 –

+0

@NathanMeunierこれは単にstackoverflowに入力するときのタイプミスです。 – Gleb

+0

「ファイルアップロード」ではなく、「ImageUrl」にテキストボックスのIDを変更するとどうなりますか? – gardarvalur

答えて

5

モデル

public class Product 
{ 
    public int ProductId { get; set; } 
    public HttpPostedFileBase Img { get; set; } //Added new property for mvc file http support 
    public string ImgUrl { get; set; } 
} 

ビュー

@using (Html.BeginForm("EditProduct", "Products", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <img src="@Url.Content(Model.ImgUrl)" /> 
    @Html.TextBoxFor(m => m.Img, new { @type = "file", @id = "file-upload" }) 
    <input type="submit" class="btn btn-primary" /> 
} 

コントローラ

0この溶液で試してみてください

説明

  • フォーム法がPOSTであり、フォームのエンコーディングタイプがマルチパート/フォームデータです。これらのパラメータは、 バイナリデータをサーバにアップロードするために必要です。

  • type = "file"のinput要素は、Choose Fileボタンと選択されたファイル名を含むフィールドを表示します。

  • 入力要素の名前は、HttpPostedFilesBaseオブジェクトのアップロードされたファイルを識別します。

Here is nice blog explained for file upload in MVC

関連する問題