How can edit the value of Html.TextBoxFor in controller before use it?

断了今生、忘了曾经 提交于 2019-12-25 08:27:49

问题


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.

I need this feature to replace some Unicode characters by some others.

Let I show my code in View and Controller:

View:

@Html.TextBoxFor(model => model.Title) // user will type "foo", in TitleTexbox! 

Controller:

 [HttpPost]
    public virtual ActionResult Create(MyModel model)
    {
     var x = model.Title;
     //I need variable x have 'fuu' instead of 'foo', replaceing "o" by "u"
     //...
    }

Should I write an override for Html.TextboxFor?


回答1:


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;
         }
    }

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 
     //...
    }

good luck.



来源:https://stackoverflow.com/questions/10946575/how-can-edit-the-value-of-html-textboxfor-in-controller-before-use-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!