使用IModelBinder自定义模型绑定
本文关键字:绑定 模型 自定义 IModelBinder 使用 | 更新日期: 2023-09-27 18:26:07
我正在尝试编写自定义模型绑定器,但它给出了一个错误,有人能告诉我哪里做错了吗?
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Models
{
public class CustomModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Ownership own = new Ownership();
own.name = controllerContext.HttpContext.Request.Form["fName"];
own.email = controllerContext.HttpContext.Request.Form["fEmail"];
own.PhoneNo = controllerContext.HttpContext.Request.Form["fPhoneNo"];
own.country = controllerContext.HttpContext.Request.Form["Country"];
own.address = controllerContext.HttpContext.Request.Form["Adres"];
own.office = controllerContext.HttpContext.Request.Form["Off"];
own.officeEmail = controllerContext.HttpContext.Request.Form["OffEmail"];
own.officeNo = controllerContext.HttpContext.Request.Form["OffNo"];
own.OwnershipType = controllerContext.HttpContext.Request.Form["OwnershipType"];
own.ProductId = controllerContext.HttpContext.Request.Form["ProductId"];
return own;
}
}
}
错误
"'CustomModelBinder'未实现接口成员'System.Web.Mvc.IModelBinder.BindModel(System.Web.Mvc.ControllerContext,System.Web.Mvc.ModelBindingContext)'
您正在使用的IModelBinder来自System.Web.ModelBinding命名空间。此接口的BindModel方法返回布尔类型的值。
bool BindModel(
ModelBindingExecutionContext modelBindingExecutionContext,
ModelBindingContext bindingContext
)
如果要使用返回对象的BindModel方法,则需要从System.Web.Mvc命名空间实现接口。
Object BindModel(
ControllerContext controllerContext,
ModelBindingContext bindingContext
)
您可以在实现此IModelBinder接口时通过提供完整的命名空间来检查它。像
public class CustomModelBinder : System.Web.Mvc.IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
Ownership own = new Ownership();
own.name = controllerContext.HttpContext.Request.Form["fName"];
own.email = controllerContext.HttpContext.Request.Form["fEmail"];
own.PhoneNo = controllerContext.HttpContext.Request.Form["fPhoneNo"];
own.country = controllerContext.HttpContext.Request.Form["Country"];
own.address = controllerContext.HttpContext.Request.Form["Adres"];
own.office = controllerContext.HttpContext.Request.Form["Off"];
own.officeEmail = controllerContext.HttpContext.Request.Form["OffEmail"];
own.officeNo = controllerContext.HttpContext.Request.Form["OffNo"];
own.OwnershipType = controllerContext.HttpContext.Request.Form["OwnershipType"];
own.ProductId = controllerContext.HttpContext.Request.Form["ProductId"];
return own;
}
}