62,046
社区成员
发帖
与我相关
我的任务
分享
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Sname)
</th>
<th>
@Html.DisplayNameFor(model => model.Ssex)
</th>
<th>
@Html.DisplayNameFor(model => model.Sage)
</th>
<th>
@Html.DisplayNameFor(model => model.Sdept)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Sname)
</td>
<td>
@Html.DisplayFor(modelItem => item.Ssex)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sage)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sdept)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Sno }) |
@Html.ActionLink("Details", "Details", new { id=item.Sno }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Sno })
</td>
</tr>
}
</table>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
namespace ConsoleApplication1
{
class User
{
public int ID { get; set; }
[DisplayName("姓名")]
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var model = new User() { ID = 1, Name = "张三" };
var mvc = new MVCHelper<User>(model);
Console.WriteLine(mvc.DisplayFor(modelitem => modelitem.ID));
Console.WriteLine(mvc.TextBoxFor(modelitem => modelitem.ID));
Console.WriteLine(mvc.DisplayFor(modelitem => modelitem.Name));
Console.WriteLine(mvc.TextBoxFor(modelitem => modelitem.Name));
}
}
class MVCHelper<TModel>
{
private TModel model { get; set; }
public MVCHelper(TModel m) { model = m; }
public string DisplayFor<T>(Expression<Func<TModel, T>> exp)
{
string s = "";
var t = ((exp.Body) as MemberExpression).Member;
if (t.GetCustomAttributes(typeof(DisplayNameAttribute), false).Any())
{
s = (t.GetCustomAttributes(typeof(DisplayNameAttribute), false)[0] as DisplayNameAttribute).DisplayName;
}
else
{
s = t.Name;
}
return string.Format("<label for='{0}'>{1}</label>", exp.Body, s);
}
public string TextBoxFor<T>(Expression<Func<TModel, T>> exp)
{
return string.Format("<input type='textbox'>{0}</input>", exp.Compile()(model));
}
}
}
<label for='modelitem.ID'>ID</label>
<input type='textbox'>1</input>
<label for='modelitem.Name'>姓名</label>
<input type='textbox'>张三</input>
Press any key to continue . . .