[ASP.NET MVC]如何使用PARTIAL VIEW(部分檢視)

  • 43779
  • 0

摘要:[ASP.NET MVC]如何使用PARTIAL VIEW(部分檢視)

1.第一個作法是:新增在~/Views/Shared/路徑下,通常是template會用到的partialView, partialview檔案名稱就跟controller的actionResult名稱相同:

這個partialView加在這路徑下:

而且內容如下,可以傳入Server端的參數喔:

<span style="color:red;">線上人數:88888</span>
<span>@ViewBag.ServerVar</span>

controller裡面是:

public ActionResult OnlineUserCounter()
{
	ViewBag.ServerVar = "Html.RenderAction is appropriate for dynamic data";
	return PartialView();
}

cshtml端這樣呼叫:注意一下,只有@Html.RenderAction吃的到Server端的參數喔

@*這樣寫效能較差,不推薦使用*@
@Html.Partial("OnlineUserCounter")
@*這樣寫效能較Html.Partial好,建議使用*@
@{
	Html.RenderPartial("OnlineUserCounter");
}
@*這樣寫的話還可以傳參數,建議使用*@
@{
	Html.RenderAction("OnlineUserCounter");
}

執行結果像是這樣:

 

 

2.第二個作法是:把cshmlt新增在~/Views/Controller名稱資料夾下,通常是Ajax用的, cshtml檔案名稱習慣會加上底線(避免直接被caller存取)

這是PartialView的檔案,加入在這邊:

這個PartialView內容是:

@model MvcGuestbook.Models.Guestbook
<table border="1">
        <tr>
            <td colspan="2" style="text-align:center">
                <h2>這是Guestbook第一筆資料</h2>
            </td>
        </tr>
    <tr>
        <td style="text-align:right;">
            @Html.DisplayNameFor(model => model.Message)
        </td>
        <td style="text-align:left;">
            @Html.DisplayFor(model => model.Message)
        </td>

    </tr>
    <tr>
        <td style="text-align:right;">
            @Html.DisplayNameFor(model => model.CreatedOn)
        </td>
        <td style="text-align:left;">
            @Html.DisplayFor(model => model.CreatedOn)
        </td>
    </tr>
</table>

Controller呼叫的方式如下:

//取得Guestbook的第一筆資料的時候,以防Server取得的是Cache,必須即時更新
[OutputCache(NoStore=true,Duration=0)]
public ActionResult GuestbookTop1Data() 
{
	var guestbook = GetGuestbookTop1Data();
	return PartialView("_GuestbookTop1Data", guestbook);	
}

執行結果如下,此時還沒設定限定Ajax專用,因此甚至用網頁打網址都可直接開:http://localhost:4102/Guestbook/GuestbookTop1Data

如果你要增加安全性,因此要設定為Ajax限定專用的話,controller改成這樣:

[OutputCache(NoStore=true,Duration=0)]
public ActionResult GuestbookTop1Data() 
{
	var guestbook = GetGuestbookTop1Data();
	//return PartialView("_GuestbookTop1Data", guestbook);
	//限定同網站的Ajax專用
	if (Request.IsAjaxRequest())
	{
		return PartialView("_GuestbookTop1Data", guestbook);
	}
	else
	{
		return Content("Fail");
	}
 
}

這時候在用網頁直接打網址開的話會出現錯誤訊息:

此時要使用這個ParitalView的話就只能用Ajax方式,如果用.net內建的方式呼叫ajax的話是這樣,記得method要用post喔,以下是cshtml的呼叫法:

<div id="GuestbookTop1Data">
	<!--兩個都要 include進來,注意順序有差-->
	<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")"  type="text/javascript"></script>
	<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"  type="text/javascript"></script>
	@Ajax.ActionLink("Ajax.ActionLink show the top 1 data in Guestbook", "GuestbookTop1Data",
new AjaxOptions { UpdateTargetId = "GuestbookTop1Data", InsertionMode = InsertionMode.Replace, HttpMethod = "POST" })
</div>

這是mvc內建的ajax的hyperlink呼叫法,點下去連結之前:

點下去連結之後:

要自訂jquery去做ajax呼叫也可以,如下,只是html與javacript要一起格式化有點麻煩,乾脆直接貼上囉:

<div id="GuestbookTop1DataByScripts">
 
                <!--兩個都要 include進來,注意順序有差-->
                <script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
                <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
                <script type="text/javascript">
                    function MyAjaxCall() {                        
                        var resultConfirm = '';
                        $.ajax({
                            type: "post",
                            url: "http://localhost:4102/Guestbook/GuestbookTop1Data",
                            url: "/Guestbook/GuestbookTop1Data",
                            //不用傳參數的話,放個大括弧就好
                            data: "{}",
                            //data: '{txtContent: "' + $("input[id*=txtTest]").val() + '" }',
                            contentType: "application/html; charset=utf-8",
                            dataType: "html",
                            async: false,//由於最後需要使用ajax取得的result的數值,必須設定為false(才會變成sync同步執行)
                            cache: false//防止ie8一直取到舊資料的話,請設定為false
                            success: function (result) {
                                //平常是取得result.d才對,但是這邊要取result
                                resultConfirm = result;                        
                            },
                            failure: function (response) {
                                //callback function result(on failure)
                                alert(response.d);
                            }
                        });
                                         
                        $("#GuestbookTop1DataByScripts").html(resultConfirm);
                    }
                </script>
                <input type='button' id='AjaxCallTop1Btn' value='AjaxCallTop1Btn' onclick='MyAjaxCall();' />
            </div>

然後執行看看,效果一樣的拉:以下是點下去ajax按鈕之前:

自訂ajaxCall點下去後: