你有多种选择。首先,您可以使用局部视图:
in layout.cshtml [or in your usecase, search page]:
@Html.Partial(your-partial-view-name)
view: headerPartial.cshtml as an example:
@if(User.Identity.IsAuthenticated) {
<span>Welcome</span> @User.Identity.Name
} else {
<span>Login or Register</span>
}
这是基本逻辑。对于您的情况,您需要这样的东西。但是,如果您必须从例如数据库加载一些数据,我建议您使用部分操作:
// in layout or search or any page you want to render partial views:
// For example you have a controller named MyPartials:
// Put this line where you want to render header:
@Html.Action("HeaderInfo", "MyPartials")
和行动:
public class MyPartialsController : Controller {
public ActionResult HeaderInfo() {
var model = retrive header needed info from db
return Partial(model);
}
}
让我详细了解您的问题,为您提供好的解决方案
更新:
认为:
控制器:CustomerController
行动:SeletedCustomer
解决方案:
1. 型号:
public class HeaderInfoModel { } // contains header data: name, email, phone, etc
public class SideInfoModel { } // dog1, cat2, etc
public class MainContentModel { } // holding main content data
// bringing all together
public class CustomerModel {
public HeaderInfoModel HeaderInfo { get; set; }
public SideInfoModel SideInfo { get; set; }
public MainContentModel MainContent { get; set; }
}
2.控制器
public class CustomerController : Controller {
public ActionResult SeletedCustomer(int id) {
// use id and retrieve data you want, from db or anywhere else you want
var model = new CustomerModel {
HeaderInfo = SomeMethodToFetchHeaderData(id),
SideInfo = SomeMethodToFetchSideData(id),
MainContent = SomeMethodToFetchMainContent(id)
};
return View(model);
}
}
3. 主视图:Customer/SeletedCustomer.cshtml
@model CustomerModel
<div id="header">
<!-- put this where you want to render header -->
@Html.DisplayFor(model => model.HeaderInfo)
</div>
<div id="side">
<!-- put this where you want to render side -->
@Html.DisplayFor(model => model.SideInfo)
</div>
<div id="main">
<!-- put this where you want to render main content -->
@Html.DisplayFor(model => model.MainContent)
</div>
4.在您的情况下,使用显示模板是最简单的方法。创建一个以DisplayTemplates
下列位置之一命名的文件夹:~/Views/Customer/
或~/Views/Shared
. 这取决于您想在哪里以及如何使用提供的模型。同样,在你的情况下,我建议创建这个:~/Views/Customer/DisplayTemplates/
. 然后在该文件夹中添加一些视图,如下所述:
4.1。创建HeaderInfoModel.cshtml
于~/Views/Customer/DisplayTemplates/
:
@model HeaderInfoModel
<div>
implement your model presentation, I mean, show the data how you want
</div>
4.2. 创建SideInfoModel.cshtml
于~/Views/Customer/DisplayTemplates/
:
@model SideInfoModel
<div>
implement your model presentation, I mean, show the data how you want
</div>
4.3. 创建MainContentModel.cshtml
于~/Views/Customer/DisplayTemplates/
:
@model MainContentModel
<div>
implement your model presentation, I mean, show the data how you want
</div>
这就对了。完毕!根据您的情况,我可以建议的最好方法是。但是,您有多种选择;这完全取决于您的项目。