Tuesday, May 16, 2017

Render Partial View Example 2

Creating Model


public class CarModel
{
public int CarID { getset; }
public string CarType { getset; }
public int CarPrice { getset; }
public string CarColor { getset; }

public List<CarModel> Listcar { getset; } // List of Car
}
}

Creating Controller

public class CarController : Controller
{
public ActionResult Index()
{
List<CarModel> objlistcar = new List<CarModel>();
            CarModel objcar = new CarModel();
            objcar.CarID = 1;
            objcar.CarColor = "Red";
            objcar.CarPrice = 20000;
            objcar.CarType = "Uday";
            objlistcar.Add(objcar);
            // add item in list
            CarModel objcar1 = new CarModel();
            objcar1.CarID = 2;
            objcar1.CarColor = "Blue";
            objcar1.CarPrice = 20000;
            objcar1.CarType = "Rajakonda Uday Kumar";

            objlistcar.Add(objcar1);  // add item in list
            objcar.Listcar = objlistcar; // assigning value to CarModel object
            return View(objcar); // Returning model
}
}
}

Creating Partial View

@model IEnumerable<WebApplication1.Models.CarModel>
<table style="background-colorrosybrownborder:dashed;">
<tr>
<td colspan="3"><h2>Child View</h2></td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.CarID)
</th>
<th>
@Html.DisplayNameFor(model => model.CarType)
</th>
<th>
@Html.DisplayNameFor(model => model.CarPrice)
</th>
<th>
@Html.DisplayNameFor(model => model.CarColor)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CarID)
</td>
<td>
@Html.DisplayFor(modelItem => item.CarType)
</td>
<td>
@Html.DisplayFor(modelItem => item.CarPrice)
</td>
<td>
@Html.DisplayFor(modelItem => item.CarColor)
</td>
</tr>
}
</table>



Creating View for Rendering Partial view

Now we have to render partial view inside Index view. For rendering view we are going to use Html Helper class that will be like as shown below

@Html.Partial("Partial View Name" , "Model which is required")
Once we add partial view inside of view that will be like as shown below 


@model  WebApplication1.Models.CarModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>View</title>
</head>
<body>
    <div>
        @Html.Partial("View", Model.Listcar)
    </div>
</body>
</html>

Output:

Finally just run application and check output that will be like as shown below. The outer most view is Parent view and the view with Brown color is Partial view (Child view).


No comments:

Post a Comment

Thank you for visiting my blog

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...