抽象类可以作为控制器动作的参数吗?

抽象类可以作为控制器动作的参数吗?,第1张

抽象类可以作为控制器动作的参数吗?

更新: 示例现在使用AJAX JSON POST

如果必须使用抽象类型,则可以提供自定义模型绑定程序来创建具体实例。一个例子如下所示:

模型/模型粘合剂

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.JavascriptStringEnpre(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()));}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5615141.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存