MVC控制器操作中的通用类型

时间:2013-12-02 12:56:32

标签: c# asp.net-mvc

我的控制器操作应该可用于一组继承抽象类Polis的模型:

public abstract class Polis
{
    /// <summary>
    /// Fields
    /// </summary>

    protected Polis()
    {
    }

    public Polis(Object input)
    {
        // Use input
    }
}

我的控制器动作指定泛型类型应继承此抽象类。但它没有看到抽象类的构造函数有一个参数。所以我必须指定它实现'new()',而我想使用带有参数的构造函数。

    public virtual ActionResult SavePolis<TModel>(PolisPostModel polisPM) where TModel : Polis, new()
    {
        if (ModelState.IsValid)
        {
            // Get the object or save a new object in the database
        }

        return Json(new
        {
            success = ModelState.IsValid,
            status = this.GetStatus(polisPM),
        });
    }

所有数据处理都在内部类中完成,因此我需要执行继承类的方法。 但是当我尝试调用控制器动作给出我的特定类型作为参数时,它会出现错误“方法没有重载'SavePolis'需要0个参数”:

@Html.Hidden("SaveMyPolis", Url.Action(MVC.Controller.SavePolis<MyPolis>())

那么调用它的正确方法是什么?并且继承的类是否可以完全可用,因此调用它的方法而不是抽象类中的方法。

2 个答案:

答案 0 :(得分:1)

我会使用自定义模型绑定器和接受子类的多个操作方法。假设有两个Polis子类:SubPolisA和SubPolisB,我会有两种操作方法:

  1. public ActionResult SavePolis(SubPolisA model)
  2. public ActionResult SavePolis(SubPolisA model)
  3. 然后我会为polis定义一个自定义模型绑定器:

    public class PolisModelBinder : System.Web.Mvc.IModelBinder
    {
       public object BindModel(ControllerContext controllerContext, 
                                ModelBindingContext bindingContext)
        {
             var form = controllerContext.HttpContext.Request.Form;
             //use hidden value to determine the model
             if(form.Get("PolisType") == "SubClassA") 
             {
                //bind SubPolisA
             }
             else 
             {
                //bind SubPolisB
             }
        }
    }
    

    然后在Application_Start()中我将使用

    注册模型绑定器
    ModelBinders.Binders.Add(typeof(SubPolisA), new PolisModelBinder());
    ModelBinders.Binders.Add(typeof(SubPolisB), new PolisModelBinder());
    

    或使用ModelBinderAttribute。如果您愿意,也可以为每个子类使用多个模型绑定器。

    *对不起代码格式

答案 1 :(得分:0)

我相信你需要做的就是:

@Html.Hidden("SaveMyPolis", Url.Action(MVC.Controller.SavePolis<MyPolis>(Model))

假设视图中的模型类型为PolisPostModel