2013-08-04 61 views
1

我有一個模型用於與外部Web服務進行通信。它應該在我的網站上調用特定的後操作。將發佈參數映射到模型

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

public ActionResult Confirmation(ConfirmationModel){ 
... 
} 

問題是它們傳遞的參數名稱不是非常容易理解的。我想將它們映射到更易讀的模型。

't_numb' ====> 'TransactionNumber' 

這可以自動完成嗎?有一個屬性可能?這裏最好的方法是什麼?

+0

檢查http://stackoverflow.com/questions/4316301/asp-net -mvc -2-綁定-A-模型屬性到一個-不同命名的值/ 4316327#4316327 – haim770

回答

1

創建一個模型綁定:

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

初始化它的Global.asax.cs:

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

然後在動作方法

[HttpPost] 
public ActionResult Confirmation(ConfirmationModel viewModel) 

你應該看到的價值t_numb出現在視圖模型的TransactionNumber屬性中。