[MVC][02]Where are user control, ajax components in MVC - Partial View

[MVC][02]Where are user control, ajax components in MVC - Partial View

Someone like me comes from asp.net web forms to MVC often wonders where is user control, ajax, footer, header components in MVC. For future convenient reference, here is going to show some simple and easy to be use examples:

1.Ajax:
first add a new cshtml:_ActorsTop2Data.cshtml, to the folder "/Views/Actors", the file name starts with underline means this is a partial view which will be used by ajax in "any other views, ex:Index.cshtml, Edit.cshtml, ....."


@model IEnumerable<MVC_5.Models.Actor>
    data returned from ajax:
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Title)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>

        </tr>
    }
</table>


add this method to Controller "ActorsController.cs", any ajax call should come from Controller class:

//"NoStore = true, Duration = 0" to prevent server to get cached data
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult ActorsTop2Data(string firstName, string lastName)
{
	using (MyDBEntities db = new MyDBEntities())
	{
		//ToList() is necessary, 
		//because using (MyDBEntities db = new MyDBEntities())
		//will automatically dispose 
		var top2Data = db.Actor.Where(ac=>ac.FirstName == firstName && ac.LastName == lastName)
			.Take(2).ToList();
		if (Request.IsAjaxRequest())
		{
			return PartialView("_ActorsTop2Data", top2Data);
		}
		else
		{
			return Content("Fail!");
		}

	}

}


Use this ajax partial view in Index.cshtml:
add following code at the end of Index.cshtml, do not forget to check the comment in code

<p></p>
<div id="ActorsTop2Data">
    <!--include these 2 .js, notice jquery-3.3.1.min.js must be included prior to jquery.unobtrusive-ajax.min.js!-->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" )" type="text/javascript"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-ajax-unobtrusive@3.2.4/jquery.unobtrusive-ajax.min.js" )" type="text/javascript"></script>
    @Ajax.ActionLink("Ajax.ActionLink passes 2 params and shows top 2 data in Actors", "ActorsTop2Data", new { firstName = "Chris", lastName = "Hemsworth" },
                    new AjaxOptions { UpdateTargetId = "ActorsTop2Data", InsertionMode = InsertionMode.Replace, HttpMethod = "POST" })
</div>

execute the project, and click the link at the end of page to get ajax result:


2. UserControl
how to use usercontrol in MVC is 95% similiar as ajax

add a new cshtml:_ActorsUserControl.cshtml, to the folder "/Views/Actors", the file name starts with underline means this is a partial view which will be used by usercontrol in "any other views, ex:Index.cshtml, Edit.cshtml, ....."


@model IEnumerable<MVC_5.Models.Actor>
    data returned from usercontrol:
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Title)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>

        </tr>
    }
</table>


add this method to Controller "ActorsController.cs", the data for usercontrol comes from here:

public ActionResult ActorsUserControlMethod(string keyWord)
{
	using (MyDBEntities db = new MyDBEntities())
	{
		//ToList() is necessary, 
		//because using (MyDBEntities db = new MyDBEntities())
		//will automatically dispose 
		var relatedData = db.Actor.Where(emp => emp.LastName.Contains(keyWord)).ToList();
		return PartialView("_ActorsUserControl", relatedData);

	}

}


​Use this usercontrol partial view in Index.cshtml:
add following code at the end of Index.cshtml, do not forget to check the comment in code

<p></p>
<div id="ActorsUserControl">
    Html.Action show the top 2 data with keyword "H" in Actors:
    @Html.Action("ActorsUserControlMethod", new { keyWord = "H" })
</div>


execute the project, and the data of usercontrol will show automatically:



Project Direct Download Link

Reference:
How can I pass parameters to an Action using Html.Action() in ASP.NET MVC?
https://stackoverflow.com/questions/3150491/how-can-i-pass-parameters-to-an-action-using-html-action-in-asp-net-mvc
[ASP.NET MVC]部分檢視詳解(partial,renderpartial,action,renderAction,renderPage...)
https://dotblogs.com.tw/kevinya/2015/11/13/153909
[ASP.NET MVC]如何使用PARTIAL VIEW(部分檢視)
https://dotblogs.com.tw/kevinya/2015/11/06/153816