【发布时间】:2013-05-22 13:37:59
【问题描述】:
这是我第一次使用 MVC,也是第一次编写 Web 应用程序。
到目前为止,我设法获得了一个员工列表视图和一个员工模型的编辑视图。
如果我需要将 25 个模型显示为列表并进行编辑,我是否必须创建 50 个不同的视图?
或者有没有办法拥有一个通用的列表视图和一个通用的编辑视图?
(在下面编辑)
解决了列表视图问题。 抱歉,代码太长了。
我创建了一个描述模型属性的 ModelPropertyInfo 类。目前我只添加了标签,但我可能会添加更多属性,例如“格式”、“输入类型”……
// Model field information class. Used by views to display model info properly
public class ModelPropertyInfo
{
public ModelPropertyInfo() { }
public string Name { get; set; }
public string Label { get; set; }
}
然后ShowInListAttribute属性类只装饰我想出现在列表视图中的模型属性
// Attribute class used to specify Labels for model fields
public class ShowInListAttribute : Attribute
{
public ShowInListAttribute(string header)
{
Header = header;
}
public string Header { get; set; }
}
还有一个 ModelBase 类,我的所有模型都将继承。此类将能够通过将其名称传递为 string
从类中获取任何属性值// Base class for all models
public class ModelBase
{
public static List<ModelPropertyInfo> ModelProperties(Type modelType)
{
List<ModelPropertyInfo> result = new List<ModelPropertyInfo>();
foreach (PropertyInfo pi in modelType.GetProperties())
{
ShowInListAttribute att = (ShowInListAttribute)pi.GetCustomAttributes(typeof(ShowInListAttribute), true).FirstOrDefault();
if (att != null)
result.Add(new ModelPropertyInfo { Label = att.Header, Name = pi.Name });
}
return result;
}
public object GetPropertyValue(string propName)
{
return this.GetType().GetProperty(propName).GetValue(this, null);
}
}
现在,这是我的 Employee 模型类
[Table("Employee")]
public class Employee : ModelBase
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public decimal ID { get; set; }
[ShowInList("First Name")]
public string FirstName { get; set; }
[ShowInList("Last Name")]
public string LastName { get; set; }
public decimal DepartmentID { get; set; }
[ShowInList("Department")]
[DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Computed)]
public string DepartmentName { get; set; }
}
所以,为了使用以上所有内容,这是我的 EmployeeController
中的 Index 方法public ActionResult Index()
{
ViewBag.Columns = ModelBase.ModelProperties(typeof(Employee));
ViewBag.Title = "Employee List";
return View("ListShared", db.Employees.ToList());
}
最后,我将使用 SharedListView 来显示我想要的任何模型的列表
@using SharedListView.Models
@model IEnumerable<ModelBase>
<h2>@ViewBag.Title</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
@foreach (ModelPropertyInfo col in ViewBag.Columns)
{
<th>
@col.Label
</th>
}
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
@foreach (ModelPropertyInfo col in ViewBag.Columns)
{
<td width='100px'>
@item.GetPropertyValue(col.Name).ToString()
</td>
}
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.GetPropertyValue("ID") }) |
@Html.ActionLink("Details", "Details", new { id=item.GetPropertyValue("ID") }) |
@Html.ActionLink("Delete", "Delete", new { id=item.GetPropertyValue("ID") })
</td>
</tr>
}
</table>
仍然停留在一个常见的编辑视图上,任何帮助将不胜感激。
再次抱歉,编辑太长了。
【问题讨论】: