2015-07-20 107 views
-1

在我的表單中,我有能力向系統添加新產品(使用MVC 5),但我有一個問題。我有這樣的代碼:將文本框轉換爲文本區

<div class="form-group"> 
    @Html.LabelFor(model => model.ProductDescription, "Description", htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.EditorFor(model => model.ProductDescription, new { htmlAttributes = new { @class = "form-control" } }) 
     @Html.ValidationMessageFor(model => model.ProductDescription, "", new { @class = "text-danger" }) 
    </div> 
</div> 

其中,如你所知創建一個文本框,我想知道用什麼來修改這個現有的代碼添加一個文本區域,而不是一個文本框的方法嗎?

編輯

@Stephen Muecke

我創建了一個名爲DisplayProductsViewModel視圖模型,它看起來像這樣:

using AccessorizeForLess.Data; 

namespace AccessorizeForLess.ViewModels 
{ 
    public class DisplayProductsViewModel 
    { 
     public string Name { get; set; } 
     public string Price { get; set; } 
     public ProductImage Image { get; set; } 
    } 
} 

然後在我的控制,我改變它看起來像這樣:

private ApplicationDbContext db = new ApplicationDbContext(); 

// GET: /Products/ 
public ActionResult Index() 
{ 
    var products = db.Products.Include(p => p.ProductImage).ToList(); 
    List<DisplayProductsViewModel> model = null; 
    foreach (Product pr in products) 
    { 
     model.Add(
      new DisplayProductsViewModel() 
      { 
       Name = pr.ProductName, 
       Image = pr.ProductImage, 
       Price = String.Format("{0:C}", pr.ProductPrice) 
      }); 
    } 

    return View(model.ToList()); 
} 

但是當我運行它模型始終爲空。你能幫助我嗎?一旦我能做到這一點,那麼我將對這一切有更好的理解。

編輯

@Stephen Muecke

我每次修改你的建議我的代碼如下:

private ApplicationDbContext db = new ApplicationDbContext(); 

// GET: /Products/ 
public ActionResult Index() 
{ 
    var products = db.Products.Include(p => p.ProductImage); 

    List<DisplayProductsViewModel> model = products.Select(p => new DisplayProductsViewModel() 
    { 
     Name = p.ProductName, 
     Image = p.ProductImage, 
     Price = string.Format("{0:C}", p.ProductPrice) }).ToList(); 

    return View(model); 
} 

,現在又被返回任何內容。

回答

3

應用[DataType(DataType.MultilineText)]屬性你的財產

[DataType(DataType.MultilineText)] 
public string Description { get; set; } 

或使用

@Html.TextAreaFor(m => m.ProductDescription, new { @class = "form-control" }) 
+0

對於我嘗試添加的數據類型屬性來我的財產在EF實體的記錄,它什麼也沒做,我會嘗試@ Html.TextAreaFor,看看是否符合我的需求。謝謝 – PsychoCoder

+1

將'DataTypeAttribute'應用於數據模型的屬性並不合適(它是一個特定於視圖的屬性)。你真的應該使用這個視圖模型。 –

+0

我是MVC的新手,你如何使用視圖模型? – PsychoCoder