2012-01-04 256 views
2

TextAreaFor代碼以下是我的模型屬性置換在Asp.net MVC剃刀

[Required(ErrorMessage = "Please Enter Short Desciption")] 
[StringLength(200)] 
public string ShortDescription { get; set; } 

而下面是我相應的視圖代碼

@Html.TextAreaFor(model => model.Product.ShortDescription, new { cols = "50%", rows = "3" }) 
@Html.ValidationMessageFor(model => model.Product.ShortDescription) 

,這是它是如何顯示在瀏覽器中,我想要的方式。 enter image description here

現在,因爲有一個bug in Microsoft's MVC3 release,我無法驗證和表單提交併產生惱人的錯誤。

請告訴我可以替代TextAreaFor的工作或任何代碼。我無法使用EditorFor,因爲有了它,我無法使用行和列參數。我想在瀏覽器中保持我的字段外觀。讓我知道應該在這種情況下

回答

4

完成在控制器的描繪這一觀點確保你已經(在你的情況Product)實例化的相關屬性,使之不爲空:

非工作示例:

public ActionResult Foo() 
{ 
    var model = new MyViewModel(); 
    return View(model); 
} 

工作例如:

public ActionResult Foo() 
{ 
    var model = new MyViewModel 
    { 
     Product = new ProductViewModel() 
    }; 
    return View(model); 
} 

另一種可能性(和一個我建議)是裝飾您的視圖模型屬性無線TH的[DataType]屬性,表示你的意圖顯示爲多行文本:

[Required(ErrorMessage = "Please Enter Short Desciption")] 
[StringLength(200)] 
[DataType(DataType.MultilineText)] 
public string ShortDescription { get; set; } 

,並在視圖中使用的EditorFor幫手:

@Html.EditorFor(x => x.Product.ShortDescription) 

至於rowscols參數,你表示關切在你的問題中,你可以簡單地使用CSS來設置textarea的寬度和高度。例如,你可以把這個文本區域在一個div或東西給定的類名:

<div class="shortdesc"> 
    @Html.EditorFor(x => x.Product.ShortDescription) 
    @Html.ValidationMessageFor(x => x.Product.ShortDescription) 
</div> 

,並在你的CSS文件中定義它的尺寸:

.shortdesc textarea { 
    width: 150px; 
    height: 350px; 
} 
+0

對不起隊友,我是不能夠做任何事情的SO最近幾個小時,因爲在這裏的外部域JavaScript。將這個代碼放在工作中,讓你知道....謝謝 – 2012-01-04 10:44:49