所以我正在开发一个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>
答案 0 :(得分:2)
我建议开始使用模型并将其返回到您的视图,而不是传递会话对象并将其投射到视图中。它会使这段代码更加干净。
这就是我构建代码的方式:
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);
}
您孩子的观点:
@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>