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

前端 未结 2 712
春和景丽
春和景丽 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<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>
    
    0 讨论(0)
  • 2020-12-31 12:55

    I have blogged about 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

    0 讨论(0)
提交回复
热议问题