我正在寻找示例代码来创建一个主/细节与c#mvc 3.
具体来说,我试图找出如何通过ajax调用部分视图的渲染.我可以把部分视图放在窗体上,但是想要在用户通过ajax从选择列表中选择一个项目之后进行填充.
谢谢
与往常一样,您从模型开始:
原文链接:https://www.f2er.com/ajax/159874.htmlpublic class Myviewmodel { public int Id { get; set; } public string Title { get; set; } } public class Detailsviewmodel { public string Foo { get; set; } public string Bar { get; set; } }
那么一个控制器:
public class HomeController : Controller { public ActionResult Index() { // TODO: don't hardcode,fetch from repository var model = Enumerable.Range(1,10).Select(x => new Myviewmodel { Id = x,Title = "item " + x }); return View(model); } public ActionResult Details(int id) { // TODO: don't hardcode,fetch from repository var model = new Detailsviewmodel { Foo = "foo detail " + id,Bar = "bar detail " + id }; return PartialView(model); } }
和相应的看法.
〜/查看/主页/ Index.cshtml:
@model IEnumerable<Myviewmodel> <ul> @Html.DisplayForModel() </ul> <div id="details"></div> <script type="text/javascript"> $(function () { $('.detailsLink').click(function () { $('#details').load(this.href); return false; }); }); </script>
〜/查看/主页/ Details.cshtml:
@model Detailsviewmodel @Model.Foo @Model.Bar
〜/浏览/首页/ DisplayTemplates / Myviewmodel.cshtml:
@model Myviewmodel <li> @Html.ActionLink(Model.Title,"details",new { id = Model.Id },new { @class = "detailsLink" }) </li>