繁体   English   中英

如何使用 Asp.Net Mvc 调用局部视图

[英]How to Call Partial View with Asp.Net Mvc

我需要在数据库上搜索,只加载视图,而不是刷新整个页面。 Js 中的一个函数在控制器上调用我的方法,当点击搜索时,控制器返回视图。

function Pesquisa()
{
  let campo = document.getElementsByName("campo");
  let pesquisa = document.getElementsByName("EdtPesquisa");
  let condicao = document.getElementsByName("pesquisa");

  let scampo = Array();
  let spesquisa = Array();
  let scondicao = Array();

  let sNomeGrid = ($(this).find("a").text());    

  for (var indice = 0; indice < pesquisa.length; indice++)
  {
    string = pesquisa[indice].value;

    if (string.trim() != "")
    {           
        scampo[indice] = campo[indice].id;
        scondicao[indice] = condicao[indice].value;
        spesquisa[indice] = pesquisa[indice].value;            
    }
  }

window.location.href = "/MenuPrincipal/RetornarView?sNomeGrid=" + "Unidade" + "&listacampo=" + scampo + "&listacondicao=" + scondicao + "&listapesquisa=" + spesquisa;

控制器

public IActionResult RetornarView(string sNomeGrid, List<string> listacampo, List<string> listacondicao, List<string> listapesquisa)
{
    var sWhere = "";

    if (listacampo.Count > 0)
    {
        Pesquisa _Pesquisa = new Pesquisa();

        sWhere = _Pesquisa.Pesquisar(listacampo, listacondicao, listapesquisa);
    }

    if (sNomeGrid == "Unidade")
    {
        var listaunidade = _UnidadeRepositorio.ListarMenu(sWhere);

        return View("Unidade", listaunidade);
    }

    return View("MenuPrincipal");
}

看法

@model IEnumerable<ApesWeb.Models.Classes.Unidade>

<div class="tabela-responsive">
<table id="tabela" class="tabela tabela-hover"
       data-toggle="table">
    <thead>
        <tr>
            <th id="idunidade" name="campo">@Html.DisplayNameFor(model => model.idunidade)</th>
            <th id="sdescricao" name="campo">@Html.DisplayNameFor(model => model.sdescricao)</th>
            <th id="sunidade" name="campo">@Html.DisplayNameFor(model => model.sunidade)</th>
            <th id="sdigitavolume" name="campo">@Html.DisplayNameFor(model => model.sdigitavolume)</th>
            <th id="spadraosistema" name="campo">@Html.DisplayNameFor(model => model.spadraosistema)</th>
        </tr>
        <tr>
            <th>
                <div class="inputWithIcon">
                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>
                    <i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
                </div>
            </th>
            <th>
                <div class="inputWithIcon">
                    <select name="pesquisa"/>
                    <input type="text" name="EdtPesquisa"/>
                    <i class="fa fa-search" aria-hidden="true"  onclick="Pesquisa()"></i>
                </div>
            </th>
            <th>
                <div class="inputWithIcon">
                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>
                    <i class="fa fa-search" aria-hidden="true"  onclick="Pesquisa()"></i>
                </div>
            </th>
            <th>
                <div class="inputWithIcon">
                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>
                    <i class="fa fa-search" aria-hidden="true"  onclick="Pesquisa()"></i>
                </div>
            </th>
            <th>
                <div class="inputWithIcon">
                    <select name="pesquisa" />
                    <input type="text" name="EdtPesquisa"/>
                    <i class="fa fa-search" aria-hidden="true"  onclick="Pesquisa()"></i>
                </div>
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var Unidade in Model)
        {
        <tr>
            <td>
                @Html.DisplayFor(modelitem => Unidade.idunidade) 
            </td>
            <td>
                @Html.DisplayFor(modelitem => Unidade.sdescricao)
            </td>
            <td>
                @Html.DisplayFor(modelitem => Unidade.sunidade)
            </td>
            <td>
                @Html.DisplayFor(modelitem => Unidade.sdigitavolume)
            </td>
            <td>
                @Html.DisplayFor(modelitem => Unidade.spadraosistema)
            </td>
        </tr>
        }
    </tbody>
</table>

返回带有列表的视图以填充表,但在此过程中整个页面都被刷新。

您可以根据需要使用以下方法之一:

方法一:如果你想使用ViewData,试试这个:

@Html.Partial("~/PathToYourView.cshtml", null, 
    new ViewDataDictionary { { "VariableName", "some value" } })

并检索传入的值:

@{
    string valuePassedIn = this.ViewData.ContainsKey("VariableName") ? 
        this.ViewData["VariableName"].ToString() : string.Empty;
}

方法二:如果你只用部分名称渲染一个部分:

@Html.Partial("_SomePartial", Model)

方法二:使用 jQuery Ajax 调用渲染 PartialView:

首先将您的正文内容包装在一个 div 中,并在 _Layout 页面中为其分配任何 id:

<div id="div-page-content" class="page-content">
    @RenderBody() 
</div>

这是在_Layout 页面中用于渲染 PartialView 的菜单项:

<ul class="sub-menu">
    <li class="nav-item  ">
        <a href="#" onclick="renderPartial(event, 'Account', '_Register')" class="nav-link">
            <span class="title">Create New User</span>
        </a>
    </li>
</ul>

在 _Layout 页面定义点击事件的 javascript 函数:

function renderPartial(e, controller, action) {
    e.preventDefault();
    e.stopPropagation();

    var controllerName = controller;
    var actionName = action;

    if (String(actionName).trim() == '') {
        return false;
    }
    if (typeof (controllerName) == "undefined") {
        return false;
    }

    var url = "/" + controllerName + "/" + actionName;

    ////Open url in new tab with ctrl key press
    //if (e.ctrlKey) {
    //    window.open(url, '_blank');
    //    e.stopPropagation();
    //    return false;
    //}

    $.ajax({
        url: url,
        data: { /* additional parameters */ },
        cache: false,
        type: "POST",
        dataType: "html",

        success: function (data) {
            var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
            if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
                requestedUrl = window.location.href;
            }

            // if the url is the same, replace the state
            if (typeof (history.pushState) != "undefined") {
                if (window.location.href == requestedUrl) {
                    history.replaceState({ html: '' }, document.title, requestedUrl);
                }
                else {
                    history.pushState({ html: '' }, document.title, requestedUrl);
                }
            }

            $("#div-page-content").html(data); 
        },
        error: function (data) { onError(data); }
    });
};

定义您的 PartialView,如下所示:

<div>
    ... partial view content goes here >
</div>            

将 Action 方法添加到 Controller 中,如下所示:

[HttpPost]
[AllowAnonymous]
public PartialViewResult _Register(/* additional parameters */)
{
    return PartialView();
}

希望这可以帮助朋友...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM