1

我有一个模型要用于与外部 Web 服务进行通信。它应该在我的网站上调用特定的发布操作。

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

public ActionResult Confirmation(ConfirmationModel){
...
}

问题是它们传递的参数名称不是很可读。我想将它们映射到我更易读的模型。

't_numb' ====> 'TransactionNumber'

这可以自动完成吗?也许有一个属性?这里最好的方法是什么?

4

2 回答 2

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)

您应该会在viewmodel 的属性中看到t_numb出现的值。TransactionNumber

于 2013-08-04T19:14:01.073 回答
0

同意模型活页夹更好:虽然这是一个替代想法

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

    // ...

    return View();
}

以及关于两者的良好阅读:http: //odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx

于 2013-08-07T20:33:30.983 回答