您可以有一个自定义值提供者:
public class MyValueProvider : IValueProvider
{
public bool ContainsPrefix(string prefix)
{
return true;
}
public ValueProviderResult GetValue(string key)
{
if (key.EndsWith("Name"))
{
var value = "john";
return new ValueProviderResult(value, value, CultureInfo.InvariantCulture);
}
else if (key.EndsWith("IPAddress"))
{
var value = "127.0.0.1";
return new ValueProviderResult(value, value, CultureInfo.InvariantCulture);
}
return null;
}
}
和相应的工厂:
public class MyValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
return new MyValueProvider();
}
}
将在以下位置注册Application_Start
:
ValueProviderFactories.Factories.Add(new MyValueProviderFactory());
现在你可以有一个控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
和一个观点:
@model MyViewModel
@Html.DisplayFor(x => x.Name)
@Html.DisplayFor(x => x.IPAddress)
@using (Html.BeginForm())
{
<button type="submit">OK</button>
}
默认模型绑定器将使用您的自定义值提供程序。