问题描述
我在MVC 3工作在我的项目,并寻找一种方式,它可以将此功能添加到我的所有Html.TextboxFor:结果
当用户键入富,并提交形式,在控制器级别我得到它模型FUU为例。
I'm working on my project in MVC 3 and searching for a way, which can add this functionality to all my Html.TextboxFor:
When user type "foo" and submit form, in controller level I get it by model as "fuu" for example.
我需要这个功能被一些人来代替一些统一code字符。
I need this feature to replace some Unicode characters by some others.
让我显示我查看code和控制器:
Let I show my code in View and 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的覆盖?
Should I write an override for Html.TextboxFor?
推荐答案
因为我从你的code明白,你从你的模型预计要准备好(已处理),当它传递给控制器action.and完成这个唯一的办法就是使用模型绑定。
但这种方法仅限于特定类型/类/模型/视图模型或任何你的名字。
as i understood from your code , you expect from your model to be ready(processed) when it passed to your controller action.and for accomplishing this the only way is using model-binding.but this approach is limited to particular type/class/model/viewmodel or whatever you name it.
您可以创建自己的模型绑定器为:
you can create your own modelBinder as:
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中注册您的自定义模型绑定
and then you most register your Custom Model Binder in Global.asax
ModelBinders.Binders.Add(typeof(MyModel),new MyCustomModelBinder());
请改变你的操作是这样的:
make change in your action like this:
[HttpPost]
public virtual ActionResult Create([ModelBinder(typeof(MyCustomModelBinder))] MyModel model)
{
var x = model.Title;
//here you will have the modified version of your model
//...
}
好运。
这篇关于如何使用它之前,控制器编辑Html.TextBoxFor的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!