Master-Detail Sample Code for MVC 3 Razor (using Ajax for details)

前端 未结 2 722
春和景丽
春和景丽 2020-12-31 12:00

I am looking for sample code to create a master/details with c# mvc 3.

Specifically, I am trying to figure out how to call via ajax the rendering of a partial view.

2条回答
  •  忘掉有多难
    2020-12-31 12:44

    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:

    @model IEnumerable
    
    
      @Html.DisplayForModel()

    ~/Views/Home/Details.cshtml:

    @model DetailsViewModel
    @Model.Foo
    @Model.Bar
    

    ~/Views/Home/DisplayTemplates/MyViewModel.cshtml:

    @model MyViewModel
    
  • @Html.ActionLink(Model.Title, "details", new { id = Model.Id }, new { @class = "detailsLink" })
提交回复
热议问题