因此,我正在进行一个MVC 3项目,该项目从遗留数据源的多(10)个表中提取到具有6个部分的主视图中。有一个表包含每个子视图的数据,因此我们决定将其存储在会话数据中,然后用所需的任何其他数据填充其余子视图。
当我们最初尝试这样做时,我们得到了会话数据的空引用异常。我已经想出了一个解决方案,但它看起来很笨拙,我认为这不是最佳实践/引入不必要的状态。
要遵循的相关代码:
这就是我们在主控制器上的功能:
public ActionResult PolicyView(string PolicyID)
{
IPolicyHolder phdata = new PolicyHolderData();
Polmast policy = phdata.GetPolicyFromUV(PolicyID);
ViewBag.FullName = policy.FULLNAME;
ViewBag.PolicyID = PolicyID;
Session["polmast"] = policy;
return View("PolicyView");
}
然后在我们的主视图中,部分子视图的链接之一:
<div id="Billing">
@{ Html.RenderAction("Billing", Session["polmast"] ); }
</div>
在子控制器中:
public ActionResult Billing(object sessiondata)
{
return PartialView("_Billing", sessiondata);
}
在儿童视角中:
@{var polmast = (Polmast)Session["polmast"];}
**snip**
<table id="premiumsgrid" class="display" border="1"
cellpadding="0" cellspacing="0" width="50%">
<thead>
<tr>
<th>Annual</th>
<th>Semi-Annual</th>
<th>Quarterly</th>
<th>Monthly</th>
</tr>
</thead>
<tbody>
<tr>
<td>@polmast.PAN</td>
<td>@polmast.PSA</td>
<td>@polmast.PQT</td>
<td>@polmast.PMO</td>
</tr>
</tbody>
</table>
我建议开始使用模型并将其返回到视图中,而不是传递会话对象并在视图中强制转换它。这将使代码更加干净。
这就是我构建代码的方式:
public ActionResult PolicyView(string PolicyID)
{
IPolicyHolder phdata = new PolicyHolderData();
Polmast policy = phdata.GetPolicyFromUV(PolicyID);
PolicyModel model = new PoliceModel() {
FullName = policy.FULLNAME,
PolicyID = PolicyID
//Populate other properties here.
};
Session["polmast"] = policy;
return View("PolicyView", model);
}
然后我会设置你的主视图(不需要用大括号包装这个调用,也不需要传递任何路由值):
<div id="Billing">
@Html.RenderAction("Billing")
</div>
子控制器:
public ActionResult Billing()
{
//Get the data out of session; it should already exist since your parent controller took care of it.
var policyData = (Polmast)Session["polmast"];
PolicyModel model = new PoliceModel() {
FullName = policy.FULLNAME,
PolicyID = PolicyID
//Populate other properties here.
};
return PartialView("_Billing", model);
}
和你的孩子的看法:
@型号Polmast狙击
<table id="premiumsgrid" class="display" border="1"
cellpadding="0" cellspacing="0" width="50%">
<thead>
<tr>
<th>Annual</th>
<th>Semi-Annual</th>
<th>Quarterly</th>
<th>Monthly</th>
</tr>
</thead>
<tbody>
<tr>
<td>@Model.PAN</td>
<td>@Model.PSA</td>
<td>@Model.PQT</td>
<td>@Model.PMO</td>
</tr>
</tbody>
</table>