我有一个像这样的复杂表单视图模型:
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] 公共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...
}
我猜我需要创建一个自定义模型出价工具。这值得吗?我会在性能或任何其他方面获得任何收益吗?或者你知道我可以做任何其他方法吗?我不知道如何正确地表达这种情况,所以我找不到任何相关的...... 提前谢谢。
答案 0 :(得分:2)
在我看来,当默认的活页夹无法处理你的情况时,总是值得创建一个自定义模型绑定器。无论如何,它将完全按照您的操作执行操作,因此不会有额外的代码(只是一个额外的类)。你将摆脱对httpcontext的依赖,并有一个更清晰的动作方法。