当ASP.NET MVC拒绝附加字段时,可以通过以下方法解决:
public class CustomModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "FieldNameToIgnore")
{
// 不处理附加字段
return;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
然后在Global.asax.cs文件中注册自定义模型绑定器:
protected void Application_Start()
{
// 注册自定义模型绑定器
ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
// 其他代码...
}
public class MyViewModel
{
public string Field1 { get; set; }
public string Field2 { get; set; }
}
在控制器中使用ViewModel来接收请求数据:
[HttpPost]
public ActionResult MyAction(MyViewModel model)
{
// 处理请求数据
return View();
}
这样就可以只接收需要的字段,而忽略附加字段。
public class CustomPropertyBinder : IPropertyBinder
{
public void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "FieldNameToIgnore")
{
// 不处理附加字段
return;
}
// 使用默认的属性绑定器
var defaultPropertyBinder = new DefaultPropertyBinder();
defaultPropertyBinder.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
然后在Global.asax.cs文件中注册自定义属性绑定器:
protected void Application_Start()
{
// 注册自定义属性绑定器
PropertyBinders.Binders.DefaultBinder = new CustomPropertyBinder();
// 其他代码...
}
这些方法可以帮助解决ASP.NET MVC拒绝附加字段的问题。根据具体的需求选择合适的方法来处理附加字段。