1

I have a model I want to use for communication with an external web service. It's supposed to call a specific post action on my website.

public class ConfirmationModel{
    ...
    public string TransactionNumber {get; set;}
}

public ActionResult Confirmation(ConfirmationModel){
...
}

The problem is the parameters names they pass are not very human-readable. And I want to map them to my more readable model.

't_numb' ====> 'TransactionNumber'

Can this be done automatically? With an attribute maybe? What's the best approach here?

Andrzej Gis
  • 13,706
  • 14
  • 86
  • 130
  • Check http://stackoverflow.com/questions/4316301/asp-net-mvc-2-bind-a-models-property-to-a-different-named-value/4316327#4316327 – haim770 Aug 04 '13 at 19:00

2 Answers2

1

Create a model binder:

using System.Web.Mvc;
using ModelBinder.Controllers;

public class ConfirmationModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var model = new ConfirmationModel();

        var transactionNumberParam = bindingContext.ValueProvider.GetValue("t_numb");

        if (transactionNumberParam != null)
            model.TransactionNumber = transactionNumberParam.AttemptedValue;

        return model;
    }
}

Initialise it in Global.asax.cs:

protected void Application_Start()
{
    ModelBinders.Binders.Add(typeof(ConfirmationModel), new ConfirmationModelBinder());
}

Then in your action method

[HttpPost]
public ActionResult Confirmation(ConfirmationModel viewModel)

You should see the value of t_numb appear in TransactionNumber property of the viewmodel.

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
0

Agree that model binder is better: here's an alternate idea though

public ActionResult Create(FormCollection values)
{
    Recipe recipe = new Recipe();
    recipe.Name = values["Name"];      

    // ...

    return View();
}

and a good read about both: http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx

MondayPaper
  • 1,569
  • 1
  • 15
  • 20