1

好吧,我有一个像这样的复杂表单视图模型:

public class TransactionFormViewModel
{
    public Session SessionRecord { get; private set; }
    public IEnumerable<Resource> ResourcePerSessionRecord { get; private set; }
    public Person PersonRecord { get; private set; }
    public decimal SubTotal { get; private set; }

    public TransactionFormViewModel(Person patient, Session session, IEnumerable<Resource> resourcePerSession)
    {
        this.PersonRecord = person;
        this.SessionRecord = session;
        this.ResourcePerSession = resourcePerSession
        this.SubTotal = CalculateSubTotal();
    }

    private decimal CalculateSubTotal()
    {
        return ResourcePerSession.Sum(x => x.Cost);
    }
}

这是我在视图中使用的模型,它(视图)看起来像这样:

        <A table that shows Person data></table>
        <A table that shows a review of the Session> </table>

       <!-- the submit button i need to complete the transaction -->
       <% using (Html.BeginForm("PayNow", "Session")) 
       {  %>
            <div id="trans-ses-footer">
                <%:Html.HiddenFor(x => x.SessionRecord.SessionID) %>
                <%:Html.HiddenFor(x => x.SessionRecord.PersonID) %>
                <%:Html.HiddenFor(x => x.SubTotal) %>

                <input type="submit" value="Pay" />
            </div>        
    <% } %>

</div>

控制器如下所示: [HttpPost] public ActionResult PayNow() { //交易模型 Transaction transaction = new Transaction();

        transaction.SessionID = int.Parse(Request.Form["SessionRecord.SessionID"]);
        transaction.PersonID = int.Parse(Request.Form["SessionRecord.PersonID"]);
        transaction.TotalCost = decimal.Parse(Request.Form["SubTotal"]);
        transaction.Paid = true;

        _sessionRepository.SaveTransaction(transaction);
        TempData["TransactionMessage"] = "The transaction was saved successfully.";

        return View();
    }

我正在使用 Request.Form 来获取交易所需的值。如果我想这样做:

Public ActionResult(Transaction transaction)
{
  if(ModelState.IsValid) 
       _transactionRepository.SaveTransaction(transaction) 
  etc...
}

我想我需要创建一个自定义模型投标人。值得麻烦吗?我会在性能或任何其他方面获得什么吗?或者你知道我可以做这种事情的任何其他方法吗?我不知道如何正确表达这种情况,所以我找不到任何相关的东西......提前谢谢你。

4

1 回答 1

2

在我看来,当默认绑定器无法处理您的情况时,创建自定义模型绑定器总是值得的。无论如何,它将完全按照您在操作中所做的事情,因此不会有额外的代码(只是一个额外的类)。并且你将摆脱对httpcontext的依赖,拥有更清晰的操作方法。

于 2010-04-30T13:59:37.803 回答