代码之家  ›  专栏  ›  技术社区  ›  goldenelf2

ASP.NET MVC 2-是否值得为此方案创建自定义模型绑定器?

  •  1
  • goldenelf2  · 技术社区  · 16 年前

    我有一个复杂的表单视图模型,如下所示:

    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公司] 公共操作结果paynow() { //事务模型 事务处理=新事务();

            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.for m来获取事务所需的值。如果我想这样做:

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

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

    1 回复  |  直到 16 年前
        1
  •  2
  •   Mattias Jakobsson    16 年前

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

    推荐文章