更新:實例現在使用AJAX JSON POST
如果你必須使用一個抽象類,你可以提供一個custom model binder創建的具體實例。一個例子如下所示:
型號/模型綁定
public abstract class Student
{
public abstract int Age { get; set; }
public abstract string Name { get; set; }
}
public class GoodStudent : Student
{
public override int Age { get; set; }
public override string Name { get; set; }
}
public class BadStudent : Student
{
public override int Age { get; set; }
public override string Name { get; set; }
}
public class StudentBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var values = (ValueProviderCollection) bindingContext.ValueProvider;
var age = (int) values.GetValue("Age").ConvertTo(typeof (int));
var name = (string) values.GetValue("Name").ConvertTo(typeof(string));
return age > 10 ? (Student) new GoodStudent { Age = age, Name = name } : new BadStudent { Age = age, Name = name };
}
}
控制器操作
public ActionResult Index()
{
return View(new GoodStudent { Age = 13, Name = "John Smith" });
}
[HttpPost]
public ActionResult Index(Student student)
{
return View(student);
}
查看
@model AbstractTest.Models.Student
@using (Html.BeginForm())
{
<div id="StudentEditor">
<p>Age @Html.TextBoxFor(m => m.Age)</p>
<p>Name @Html.TextBoxFor(m => m.Name)</p>
<p><input type="button" value="Save" id="Save" /></p>
</div>
}
<script type="text/javascript">
$('document').ready(function() {
$('input#Save').click(function() {
$.ajax({
url: '@Ajax.JavaScriptStringEncode(Url.Action("Index"))',
type: 'POST',
data: GetStudentJsonData($('div#StudentEditor')),
contentType: 'application/json; charset=utf-8',
success: function (data, status, jqxhr) { window.location.href = '@Url.Action("Index")'; }
});
});
});
var GetStudentJsonData = function ($container) {
return JSON.stringify({
'Age': $container.find('input#Age').attr('value'),
'Name': $container.find('input#Name').attr('value')
});
};
</script>
加入的global.asax.cs
protected void Application_Start()
{
...
ModelBinders.Binders.Add(new KeyValuePair<Type, IModelBinder>(typeof(Student), new StudentBinder()));
}
我覺得參數必須是一個具體的type.No抽象類型或接口類型是允許的。 – 2011-05-02 19:04:24