我在mvc3中创建了一个Web应用程序,并创建了两个局部视图 一个控制两个下拉列表。 第二个是webgrid,显示来自数据库的数据。
partialview1.cshtml
@model Mapping.Models.SecurityIdentifierMapping
@using (Html.BeginForm("Mapping", "Home"))
{
@Html.DropDownList("SecurityID", Model.PricingSecurityID, "-- Select SecurityID --")
<br />
@Html.DropDownList("CUSIPID", Model.PricingSecurityID, "-- Select CUSIPID --")
<br />
<button type="submit">Map</button>
}
partialview2.cshtml
@model IEnumerable<Mapping.Models.SecurityIdentifierMapping>
@{
ViewBag.Title = "Mapping";
WebGrid grid = null;
if (Model.Count() > 0 ){
grid = new WebGrid(source: Model,
defaultSort: "Id",
canPage: true,
canSort: true,
rowsPerPage:20);
}
}
<h2>Mapping</h2>
@if (grid != null)
{
@grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("", header: null, format: @<text>@Html.ActionLink("Edit", "Edit", new { id = (int)item.id }) @Html.ActionLink("Delete", "Delete", new { id = (int)item.id })</text>),
grid.Column("PricingSecurityID"),
grid.Column("CUSIP")
)
)
}
<br />
<p>
@Html.ActionLink("Back", "Index")
</p>
in index.cshtml
<div>
@Html.Partial("_ControlsPartial",)
</div>
<div>
@Html.Partial("_WebGridPartial")
</div>
inside Indexcontroller.cs in Index()
public ActionResult Index()
{
//FOR POPULATE DROPDOWN
//SecurityIdentifierMapping objModel = new SecurityIdentifierMapping();
//objModel.PricingSecurityID = objRepository.GetPricingSecurityID();
//objModel.CUSIP = objRepository.GetCUSIP();
//return View(objModel);
//FOR DISPLAY DATA IN WEBGRID
return View(dbContext.SecurityIdentifierMappings);
}
此处问题webgrid partial view
正在@model IEnumerable<Mapping.Models.SecurityIdentifierMapping>
和
controlpartilview
正在@model Mapping.Models.SecurityIdentifierMapping
所以我如何创建一个VIEWMODEL.cs一个新的类,它将具有两个模型,我如何在索引中写入(())因此,该方法也将在网页中播放并显示数据?
答案 0 :(得分:3)
为什么不创建一个包含两个属性的自定义View Model类:
public class SecurityIdentifierMappingViewModel
{
public IEnumerable<SecurityIdentifierMapping> MappingList {get; set; }
public SecurityIdentifierMapping Mapping {get; set; }
}
然后,您可以将此自定义视图模型传递给Index视图,并将相应的属性作为每个partials的视图模型传递
您的索引操作将如下所示:
public ActionResult Index()
{
// single mapping
var mapping = new SecurityIdentifierMapping();
maping.PricingSecurityID = objRepository.GetPricingSecurityID();
mapping.CUSIP = objRepository.GetCUSIP();
var viewModel = new SecurityIdentifierMappingViewModel
{
Mapping = mapping,
MappingList = dbContext.SecurityIdentifierMappings.ToList()
};
return View(viewModel);
}
在Index.cshtml
:
@model SecurityIdentifierMappingViewModel
<div>
@Html.Partial("_ControlsPartial", Model.Mapping)
</div>
<div>
@Html.Partial("_WebGridPartial", Model.MappingList)
</div>