MVC 3 Razor 的主从示例代码(使用 Ajax 获取详细信息)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5532568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Master-Detail Sample Code for MVC 3 Razor (using Ajax for details)
提问by David
I am looking for sample code to create a master/details with c# mvc 3.
我正在寻找示例代码来使用 c# mvc 3 创建主/详细信息。
Specifically, I am trying to figure out how to call via ajax the rendering of a partial view. I am able to put the partial view on the form but want to populate it after a user has selected an item from a select list via ajax.
具体来说,我试图弄清楚如何通过 ajax 调用局部视图的渲染。我可以将部分视图放在表单上,但希望在用户通过 ajax 从选择列表中选择一个项目后填充它。
thx
谢谢
回答by Darin Dimitrov
As always you start with the model:
与往常一样,您从模型开始:
public 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; }
}
then a controller:
然后是一个控制器:
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);
}
}
and corresponding views.
和相应的意见。
~/Views/Home/Index.cshtml:
~/Views/Home/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>
~/Views/Home/Details.cshtml:
~/Views/Home/Details.cshtml:
@model DetailsViewModel
@Model.Foo
@Model.Bar
~/Views/Home/DisplayTemplates/MyViewModel.cshtml:
~/Views/Home/DisplayTemplates/MyViewModel.cshtml:
@model MyViewModel
<li>
@Html.ActionLink(Model.Title, "details", new { id = Model.Id }, new { @class = "detailsLink" })
</li>
回答by Muhammad Adeel Zahid
I have bloggedabout creating master detail form using asp.net mvc where you can add n child records on clietn side without the need of sending ajax request just to bring the editor fields for child records. it used jquery templates
我已经写了一篇关于使用 asp.net mvc 创建主详细信息表单的博客,您可以在其中添加 n 个子记录,而无需发送 ajax 请求来为子记录带来编辑器字段。它使用了 jquery 模板

