12 November 2015

How to use partial view in MVC, an example

Here is the index page

@model  WebApplication1.Models.GridData
<!doctype html>
@{Layout = null;}
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Home</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
</head>
<body>
   <h1>Header</h1>
        <input type="button" name="btnGetJob" id="btnGetJob" value="GetJob" class="Button" onclick="GetJob();" />
        <div id="divDataGrid">
            @Html.Partial("_DataGrid", Model)
        </div>
    <script>
        function GetJob()
        {$.ajax({
                        type: "POST",
                        url: "/Home/_DataGrid",
                        success: function (data) {
                            $('#divDataGrid').html(data);
                        },
                        error: function () {
                            alert('error');
                        },
                        complete: function () {}
                   })
        }
    </script>
</body>
</html>

Here is the partial view

@model WebApplication1.Models.GridData
@{Layout = null;}
<table class="table">
    <tr>
        <th>
            @Html.DisplayTextFor(model => model.message)
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model.jobs)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Job1)
            </td>

        </tr>
    }
</table>

Here is the data model 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class GridData
    {
        public string message { get; set; }
        public  List<Job> jobs { get; set; }

        public GridData()
        {
            GraphEntities db = new GraphEntities();
            jobs = db.Jobs.ToList();
        }
    }
}

Here is the controller

    public class HomeController : Controller
    {
        private static int SessionCount = 0;
        public ActionResult Index()
        {
            GridData gd = new GridData();
            gd.message = SessionCount.ToString();
            return View(gd);
        }
        public ActionResult _DataGrid()
        {
            SessionCount++;
            GridData gd = new GridData();
            gd.message = SessionCount.ToString();
            return View(gd);
        }
        ...

Here is the output


No comments:

Post a Comment