小编典典

MVC 3 Razor的主从样本代码(有关详细信息,请使用Ajax)

ajax

我正在寻找使用C#mvc 3创建主/细节的示例代码。

具体来说,我试图弄清楚如何通过ajax调用部分视图的呈现。我可以将部分视图放在表单上,​​但要在用户通过Ajax从选择列表中选择一个项目后填充它。

谢谢


阅读 208

收藏
2020-07-26

共1个答案

小编典典

与往常一样,您从模型开始:

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; }
}

然后是一个控制器:

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);
    }
}

和相应的视图。

~/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

@model DetailsViewModel
@Model.Foo
@Model.Bar

~/Views/Home/DisplayTemplates/MyViewModel.cshtml

@model MyViewModel
<li>
    @Html.ActionLink(Model.Title, "details", new { id = Model.Id }, new { @class = "detailsLink" })
</li>
2020-07-26