Asp.net mvc 5 将textbox转换为textarea
在我的表格中,我有能力向系统中添加新产品(使用MVC5),但我有一个问题。我有以下代码:Asp.net mvc 5 将textbox转换为textarea,asp.net-mvc-5,Asp.net Mvc 5,在我的表格中,我有能力向系统中添加新产品(使用MVC5),但我有一个问题。我有以下代码: <div class="form-group"> @Html.LabelFor(model => model.ProductDescription, "Description", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @
<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>
然后在我的控制器中,我将其更改为:
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());
}
private ApplicationDbContext db=new ApplicationDbContext();
//获取产品/
公共行动结果索引()
{
var products=db.products.Include(p=>p.ProductImage.ToList();
列表模型=null;
foreach(产品中的产品pr)
{
模型。添加(
新的DisplayProductsViewModel()
{
Name=pr.ProductName,
Image=pr.ProductImage,
Price=String.Format(“{0:C}”,pr.ProductPrice)
});
}
返回视图(model.ToList());
}
但是当我运行它时,model总是空的。你能帮我一下吗,一旦我能让这一切顺利进行,我就会对这一切有更好的了解
编辑
@斯蒂芬·穆克
我根据您的建议修改了我的代码:
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);
}
private ApplicationDbContext db=new ApplicationDbContext();
//获取产品/
公共行动结果索引()
{
var products=db.products.Include(p=>p.ProductImage);
列表模型=产品。选择(p=>newdisplayproductsviewmodel()
{
Name=p.ProductName,
Image=p.ProductImage,
Price=string.Format(“{0:C}”,p.ProductPrice)}).ToList();
返回视图(模型);
}
现在没有返回任何内容。将[DataType(DataType.multilitext)]
属性应用于您的属性
[DataType(DataType.MultilineText)]
public string Description { get; set; }
或使用
@Html.TextAreaFor(m => m.ProductDescription, new { @class = "form-control" })
对于记录,我尝试将DataType属性添加到EF实体中的我的属性中,但没有任何效果,我将尝试@Html.TextAreaFor,看看这是否符合我的需要。感谢将
DataTypeAttribute
应用于数据模型的属性实际上并不合适(它是视图特定的属性)。你真的应该为此使用视图模型。我是MVC新手,你如何使用视图模型?太长,无法在注释中涵盖,但请参考索引方法更改List model=new List()代码>但我建议您只使用List model=products.Select(p=>newdisplayproductsviewmodel(){Name=ProductName,Image=..}).ToList()代码>
@Html.TextAreaFor(m => m.ProductDescription, new { @class = "form-control" })