Friday, July 29, 2011

ASP.NET MVC 3 Razor html render partial, page, action, load page using ajax

@*controller is not working, path is required *@
@*RenderPage("~/Views/Home/Simple.cshtml") *@

@*controller is not working, path load from ~/Views/Shared/_LogOnPartial.cshtml *@
@*{ Html.RenderPartial("_LogOnPartial"); }*@

@*controller is working, path load from ~/Views/{controller}/{action}.cshtml *@
@*{ Html.RenderAction("Simple", "Home"); }*@
@*Html.Action("Simple", "Home")*@

Simple.cshtml is

if Layout == null then only write a html in simple.cshtml
else load layout.cshtml with simple.cshtml

Хар ухаанаар зөвхөн simple.cshtml доторхи html ийг ( магадгүй нэр хуудас дотор хэд хэдэн асtion ажиллуулах гэж байгаа бол ийм шаардлага гарна )
@{        Layout = null;       }
болгох хэрэгтэй. тэгэхгүй бол ( Layout = null; ийм код байхгүй л бол ) бүх хуудас дуудагдаж давхар давхар тагууд харагдана гэсэн үг.
Хэрэв AJAX аар тухайн хуудлыг дангаар нь дуудах гэж байгаа бол заавал Layout = null; гэх албагүй хоосон орхиход л болно

Жишээ нь: Ajax ашиглан List.cshtml г дуудах бол нэг иймэрхүү код байж болно


~/Views/Admin/_MainLayout.cshtml байна

~/Views/Admin/Menu/Index.cshtml

@{
    this.setLayout("_MainLayout", true);
    ViewBag.Title = "Цэс бүртгэх";
    var listUrl = WebSites.Current.FullName + "/Admin/Part/Menu/List/";
    var editUrl = WebSites.Current.FullName + "/Admin/Part/Menu/Edit/";
    var deleteUrl = WebSites.Current.FullName + "/Admin/Part/Menu/Delete/";
    var editing = WebUtil.checkUrlIsSession(editUrl);
}
@section Commands {
    <ul class="command-tabs">
        <li class="tab active_tab"><a href="javascript:void(0)" onclick="listMenu();"><span>
            Жагсаалт</span></a></li>
        <li class="tab"><a href="javascript:void(0)" onclick="createMenu();"><span>Шинэ</span></a></li>
    </ul>
}
@section Types {
    @{
        var menuTypes = Util.enumToList(typeof(MenuTypeEnum));
        <text><span>Цэсний төрөл: </span><select onchange="listMenu();" id="MenuTypeCode" class="select">
            @foreach(var mt in menuTypes) {
                <option value="@mt.Value">@mt.Text</option>
            }
        </select>
        </text>   
    }
}
<script type="text/javascript">
    function listMenu() {
        $("#content").ajaxGet("@listUrl?MenuTypeCode=" + $("#MenuTypeCode").val());
        return false;
    }
    function createMenu() {
        $("#content").ajaxGet("@editUrl");
        return false;
    }
    function changeClass(sel) {
        $("ul.command-tabs > li > a").parent().removeClass("active_tab");
        $(sel).parent().addClass("active_tab");
    }
    $(function () {
        var editing = "@editing".toLowerCase();
        var alla = $("ul.command-tabs > li > a");
        $(alla).click(function (event) {
            changeClass(event.currentTarget);
        });
        if (editing == "true") {
            changeClass($("ul.command-tabs > li > a[onclick*='createMenu()']"));
            createMenu();
        } else
            $("#MenuTypeCode").change();
    });
</script>


~/Views/Admin/Menu/List.cshtml

@model IEnumerable<MenuInfo>
@{
    Layout = null;
}
<table id="grid" class="tablesorter">
    <thead>
        <tr>
            <th>
                Дээд цэс
            </th>
            <th>
                Нэр
            </th>
            <th>
                Хэсгийн нэр
            </th>
            <th>
                Цэсний төрөл
            </th>
            <th>
                Тайлбар
            </th>
            <th>
                Холбоос
            </th>
            <th>
                Дугаарлалт
            </th>
            <th>
                Идэвхитэй?
            </th>
            <th>
                Хэрэглэгч
            </th>
            <th colspan="2">
                Комманд
            </th>
        </tr>
    </thead>
    <tbody>
        @if (Model != null)
        {
            foreach (var item in Model)
            {
            <tr>
                <td>
                    @item.ParentMenu.Name
                </td>
                <td>
                    @item.Name
                </td>
                <td>
                    @item.Category.Name
                </td>
                <td>
                    @item.MenuTypeCode.ToText(typeof(MenuTypeEnum))
                </td>
                <td>
                    @item.Descr
                </td>
                <td>
                    @item.LinkText
                </td>
                <td>
                    @item.Ordering
                </td>
                <td>
                    @item.IsActive.ToText()
                </td>
                <td>
                    @item.ModifiedName
                </td>
                <td>
                    <a class="img-item-delete" href="#">
                        <img alt="" src="@Url.Content("~/Content/admin/images/delete-32.png")" height="32" width="32"/></a>
                </td>
                <td>
                    <a class="img-item-edit" href="#">
                        <img alt="" src="@Url.Content("~/Content/admin/images/edit-32.png")" height="32" width="32"/></a>
                </td>
            </tr>
            }
        }
    </tbody>
</table>
<div id="pager" class="pager"></div>
<script type="text/javascript">
    $(function () {
        $("#grid")
        .tablesorter({ widthFixed: true, widgets: ['zebra'] })
        .tablesorterPager({ container: $("#pager") });
    });
</script>

No comments: