我正在使用MVC 3中的项目并搜索一种方法,可以将此功能添加到我的所有Html.TextboxFor中:
当用户键入“foo”并提交表单时,在控制器级别我将其作为“fuu”以模型获取。例如。
我需要此功能来替换其他一些Unicode字符。
让我在View和Controller中显示我的代码:
查看:
@Html.TextBoxFor(model => model.Title) // user will type "foo", in TitleTexbox!
控制器:
[HttpPost]
public virtual ActionResult Create(MyModel model)
{
var x = model.Title;
//I need variable x have 'fuu' instead of 'foo', replaceing "o" by "u"
//...
}
我应该为Html.TextboxFor写一个覆盖吗?
答案 0 :(得分:1)
正如我从你的代码中所理解的那样,你希望模型在传递给你的控制器动作时准备好(处理完)。为了实现这个目的,唯一的方法就是使用模型绑定。 但是这种方法仅限于特定的类型/类/模型/视图模型或任何您的名称。
您可以创建自己的modelBinder:
public class MyCustomModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.HttpContext.Request;
var myModel= (MyModel ) base.BindModel(controllerContext, bindingContext) ?? new MyModel ();
myModel.Title.Replace('o','u');
return myModel;
}
}
然后您最常在Global.asax
中注册自定义模型活页夹 ModelBinders.Binders.Add(typeof(MyModel),new MyCustomModelBinder());
改变你的行动:
[HttpPost]
public virtual ActionResult Create([ModelBinder(typeof(MyCustomModelBinder))] MyModel model)
{
var x = model.Title;
//here you will have the modified version of your model
//...
}
祝你好运。