0

我有一个带有一个参数的标准 html 表单 POST 请求。

表格数据:

model:{"Id":"2901179e-553e-4c9c-8c5c-281822ff2d11","Name":"T1","Sessions":[{"Id":"","Type":5,"Version":null,"Name":"","BestLapPoints":null,"TimeOfDayMins":1080,"hours":18,"minutes":0,"MaxLaps":null,"DurationMins":null,"Description":"","Points":[]},{"Id":"","Type":7,"Version":null,"Name":"","BestLapPoints":null,"TimeOfDayMins":1200,"hours":20,"minutes":0,"MaxLaps":null,"DurationMins":null,"Description":"","Points":[{"Position":1,"Points":10},{"Position":2,"Points":8},{"Position":3,"Points":6},{"Position":4,"Points":5},{"Position":5,"Points":4},{"Position":6,"Points":3},{"Position":7,"Points":2},{"Position":8,"Points":1}]}]}

它是一个映射到 MVC 模型类的 json 序列化对象。

我想配置以模型为参数的控制器操作,以自动将 json 字符串从“模型”变量形式反序列化为特定的模型类

[HttpPost]
public ActionResult DoSomething(DomainModel model)
    {
    }

我还想避免为该模型编写自定义模型绑定器,而是使用适用于任何类似场景的通用模型。

有任何想法吗?

谢谢,斯蒂沃

4

1 回答 1

0

您可以使用自己的自定义模型绑定器:

public class CustomModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext){

       // Here you can process request body, that how you want
       HttpRequestBase request = controllerContext.HttpContext.Request;

       // Return your model
       return new CustomModel{ ... };

    }
}

然后您可以在 Application_Start 中将此模型绑定器绑定到您的模型:

protected void Application_Start()
{
    ...
    ModelBinders.Binders.Add(typeof(CustomModel), new CustomModelBinder());
}

或者您可以直接在 ActionResult 中设置 Model binder:

public ActionResult YourAction([ModelBinder(typeof(CustomModelBinder))] CustomModel model){
   ...
}
于 2013-08-22T07:02:53.213 回答