如何将参数与模型一起传递?

时间:2018-07-17 08:47:04

标签: asp.net-mvc parameters model routing

这是我的View(型号ActivityViewModel):

@model GPMS.Models.ActivityViewModel
<div class="tab-pane" id="managepayments" role="tabpanel">
    @{ Html.RenderPartial("_Payments", Model.Payments); }
</div>

渲染部分(模型IEnumerable<GPMS.Models.PaymentViewModel>):

@model IEnumerable<GPMS.Models.PaymentViewModel>
@using (Ajax.BeginForm("SavePayments", "Activities", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "DynamicContainer", InsertionMode = InsertionMode.Replace, OnBegin = "AjaxBeginFormOnBegin", OnComplete = "AjaxBeginFormOnComplete", OnSuccess = "AjaxBeginFormOnSuccess", OnFailure = "AjaxBeginFormOnFailure" }))
{
    @Html.AntiForgeryToken()
    <!-- My Form -->
}   

向我的控制器的Ajax发送Action请求:

public ActionResult SavePayments(IEnumerable<PaymentViewModel> payments)
{
    if (ModelState.IsValid) {
        // code; here I need ActivityViewModel.ID
    }
}

问题是:如何将我的活动ID存储在SavePayments中并传递给该ActivityViewModel.ID?我可以路由吗?

我不想将整个ActivityViewModel传递给SavePayments,否则我需要照顾ModelState.IsValid检查的必填字段。

1 个答案:

答案 0 :(得分:1)

一种选择是使用Html.Partial的重载通过ID传递additionalViewData,然后在部分视图中检索它,并将其作为路由值添加为表单。 / p>

在主视图中

@{ Html.RenderPartial("_Payments", Model.Payments, new ViewDataDictionary { { "ID", Model.ID} }); }

在局部

@using (Ajax.BeginForm("SavePayments", "Activities", new { id = ViewData["ID"] }, new AjaxOptions { ....

然后在POST方法中为ID添加一个参数

public ActionResult SavePayments(int id, IEnumerable<PaymentViewModel> payments)