0

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
A.Dara
  • 784
  • 10
  • 23
  • can you make your question more clear? – Behnam Esmaili Jun 08 '12 at 10:07
  • I have some views. each view has some textbox. Before MVC, I had a method which correct my input text, then save it in db. for example I want to replace all 'a' by 'b'. simply I call that method every time I use the text of inputs. Now in MVC, I'm searching for a generic way, which apply to all Html.TextboxFor in views. – A.Dara Jun 08 '12 at 10:29
  • the method you want to be generic can not be specific to a view item (e.g: TextBoxFor) .but it can be specific to a "model" or "view model". – Behnam Esmaili Jun 08 '12 at 10:37
  • if what you want to do is making changes to data posted from client and then storing it in the db.you can use custom model binding for particular type. – Behnam Esmaili Jun 08 '12 at 10:41
  • yes, you are right! I need making changes to the posted data from client and then storing it. – A.Dara Jun 08 '12 at 11:32

1 Answers1

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.

Behnam Esmaili
  • 5,835
  • 6
  • 32
  • 63