【问题标题】:Load partial view on button click单击按钮时加载部分视图
【发布时间】:2013-01-28 16:26:26
【问题描述】:

这个问题可能会重复,但我有一些问题。我的页面中有一个下拉列表和搜索按钮。我在更改事件的下拉列表中将视图与模型绑定。并且当单击在下拉列表中选择的关于记录列表的搜索按钮值时,将显示在部分视图中。这一切都正确完成如下:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ApricaCRMEvent.Models.CRM.DatabaseEntities.CRM_Doctor_Request>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    MDLNoDDLIndex
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <script src="../../Scripts/jquery.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery-migrate-1.0.0.js" type="text/javascript"></script>

    <script type="text/javascript">
        //script for binding drop down list value from view to model
        $("#viewlist").hide();
        function TestFun() 
        {
            var mdlno = $("#ddlMDLNo").val();
            var txtmdlno = document.getElementById("Request_For_Id");
            txtmdlno.value = mdlno;
            //alert(txtmdlno.value);
           $("#viewlist").hide();
        }
         var mdlno = $("#ddlMDLNo").val();
         function Datalist(mdlno) {
             $("#viewlist").show();
             $.ajax({
                 url: "/Search/MDLNoDataList", //url or controller with action
                 type: "POST",
                 data: mdlno,
                 dataType: "html",

                 success: function (data) {

                     $("#viewlist").html(data); //target div id
                 },
                 error: function () {
                     alert("No Projects Found");
                     $("#viewlist").html('there is error while submit');
                 }
             });
         }


        //$(function () { $("#btnclick").click(function () { $("#viewlist").load('/Search/MDLNoDataList') }); });

        //script for loading partial view into div tag "viewlist"

</script>
<div>
<h2>Search by MDLNo</h2>

    <% using (Html.BeginForm())
    { %>

         <%: Html.ValidationSummary(true, "Profile Updation was unsuccessful. Please correct the errors and try again.") %>

          Select MDLno 

            <%= Html.DropDownList("ddlMDLNo", ViewData["MDLno"] as SelectList, "--Select One--", new { onchange = "TestFun()" })%> 
            <%: Html.HiddenFor(model => model.Request_For_Id) %>

            <input type="submit" value="search" name="SearchMDLNo" id="btnclick" onclick ="Datalist(a)"/>    
            <div id="viewlist"><%Html.RenderAction("MDLNoDataList"); %> </div> <%--partial view should be loaded here.--%>

    <% } %> 

</div>

</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>

一切正常,但.. div 标签的部分视图在单击搜索按钮之前显示。我想要那个..当我点击按钮时部分视图加载

为此我已经尝试过这段代码:

$("#btnclick").click(function () { $("#viewlist").load('/Search/MDLNoDataList.ascx') });

我也尝试过 .show() 和 .hide() 但问题是 .. 每当我点击按钮时,整个页面都会刷新,所以 .. 加载部分视图没有正确完成。

控制者:

 public ActionResult MDLNoDDLIndex()
        {
            ViewData["MDLno"] = new SelectList(CRMSearchReportDL.getAllMDLno(), "Request_For_Id", "Request_For_Id");
            return View();
        }

        [HttpPost]
        public ActionResult MDLNoDDLIndex(CRM_Doctor_Request model)
        {
            ViewData["MDLno"] = new SelectList(CRMSearchReportDL.getAllMDLno(), "Request_For_Id", "Request_For_Id");

            //mdlnoObj = SearchMDLNoDL.getMDLData(model.Request_For_Id);
            return View();
        }


        public ActionResult MDLNoDataList()
        {
            List<CRM_Doctor_Request> drlist = new List<CRM_Doctor_Request>();
            return PartialView(drlist);
        }
        [HttpPost]
        public ActionResult MDLNoDataList(CRM_Doctor_Request model)
        {
            return PartialView(CRMSearchReportDL.getMDLNoWiseDetails(model.Request_For_Id));
        }

【问题讨论】:

    标签: jquery asp.net-mvc partial-views


    【解决方案1】:

    我已将我所有的 sn-ps 建议编译到我认为可以为您提供所需内容的标记中。如下。

    请记住,我刚刚在记事本中输入了此内容,因此可能存在语法错误,但该策略应该可以帮助您到达需要的位置。

    注意:我们正在尝试使用 AJAX 技术,所以我们真的不想回发表单,因为这会导致整个页面刷新,因此,提交按钮必须变成一个普通的按钮

    所以我们的策略是:

    • 渲染主要的表单元素并
    • 处理以下任一情况:
      • 按钮点击事件或
      • 下拉菜单更改事件——在这种情况下,我们必须完全省略按钮。

    如果我们只想在按钮被点击后更新结果,那么:

    单击按钮时,我们会获取包含结果网格的局部视图,并将#viewlist 中的整个内部 HTML 替换为局部视图的 HTML。

    我们真的不需要隐藏#viewlist。我们可以将其留空,或者显示一些其他 HTML,其中包含没有结果的通知文本,或者告诉用户该做什么的说明。

    如果我们想在下拉列表中的值更改后立即更新结果,那么:

    我们保留下拉菜单的更改处理程序并省略按钮的单击处理程序(以及整个按钮)。

    <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ApricaCRMEvent.Models.CRM.DatabaseEntities.CRM_Doctor_Request>" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
        MDLNoDDLIndex
    </asp:Content>
    
    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <div>
            <h2>Search by MDLNo</h2>
            <% using (Html.BeginForm()) { %>
            <%: Html.ValidationSummary(true, "Profile Updation was unsuccessful. Please correct the errors and try again.") %>
                Select MDLno
    
                <%= Html.DropDownList("ddlMDLNo", ViewData["MDLno"] as SelectList, "--Select One--" }) %>
                <%: Html.HiddenFor(model => model.Request_For_Id) %>
    
                <!-- delete this line if you decide to keep the dropdown change event handler and omit the button click event handler -->
                <input id="btnclick" name="SearchMDLNo" type="button" value="search" />
    
                <div id="viewlist">
                <!-- this partial view should return the result grid or should return an element stating either "No data" or some instructions -->
                <%: Html.Action("MDLNoDataList") %>
                </div>
            <% } %> 
        </div>
    
        <script type="text/javascript" src="~/Scripts/jquery.js"></script>
        <script type="text/javascript" src="~/Scripts/jquery-migrate-1.0.0.js"></script>
        <script type="text/javascript">
    
            // NOTE : the document ready handler looks like this:
            // $(function () {
            //     code placed here waits for the DOM to fully load before it is executed
            //     this is very important so as to avoid race conditions where sometimes the code
            //     works but other times it doesn't work, or varies from browser to browser or
            //     based on connection speed
            // });
    
            $(function () {
                // NOTE : keep ONLY one of either $('#ddlMDLNo').change(...) or $('#btnclick').click(...)
    
                // attach the change event handler in an unobtrusive fashion, rather than directly on
                // the DOM element
                $('#ddlMDLNo').change(function () {
                    var mdlno = $('#ddlMDLNo').val();
    
                    $.ajax({
                        url: "/Search/MDLNoDataList",
                        type: "POST",
                        data: {
                            mdlno: mdlno
                        },
                        dataType: "html",
                        success: function (data) {
                            $("#viewlist").html(data);
                        },
                        error: function () {
                            alert("No Projects Found");
                            $("#viewlist").html('An error has occurred');
                        }
                    });
                });
    
                // attach the click event handler in an unobtrusive fashion, rather than directly on
                // the DOM element
                $('#btnclick').click(function () {
                    var mdlno = $('#ddlMDLNo').val();
    
                    $.ajax({
                        url: "/Search/MDLNoDataList",
                        type: "POST",
                        data: {
                            mdlno: mdlno
                        },
                        dataType: "html",
                        success: function (data) {
                            $("#viewlist").html(data);
                        },
                        error: function () {
                            alert("No Projects Found");
                            $("#viewlist").html('An error has occurred');
                        }
                    });
                });
    
            });
        </script>
    </asp:Content>
    
    <asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server">
    </asp:Content>
    

    【讨论】:

      【解决方案2】:

      脚本

      <script type="text/javascript">
      $(function () {
          $('form').submit(function () {
              if ($(this).valid()) {
                  $.ajax({
                      url: this.action,
                      type: this.method,
                      data: $(this).serialize(),
                      beforeSend: function () {
      
                      },
                      complete: function () {
      
                      },
                      success: function (result) {
                         $("#viewlist").html(result);
                      }
                  });
              }
              return false;
          });
      });
      </script>
      

      将 HtmlBeginForm 选项添加到 HtmlBegin 表单,如下所示:

      <% using (Html.BeginForm("MDLNoDataList", "Search", FormMethod.Post, new { id = "form1" }))
          { %>
      
           <%: Html.ValidationSummary(true, "Profile Updation was unsuccessful. Please correct the errors and try again.") %>
      
          Select MDLno 
      
          <%= Html.DropDownList("ddlMDLNo", ViewData["MDLno"] as SelectList, "--Select One--", new { onchange = "TestFun()" })%> 
          <%: Html.HiddenFor(model => model.Request_For_Id) %>
      
           <input type="submit" value="search" name="SearchMDLNo" id="btnclick" />    
      <% } %> 
      

      【讨论】:

      • 我尝试了两种方式.. 根据您的建议。但是每当我点击搜索按钮时,div标签中都没有显示任何内容。
      • 这段代码正在运行,但现在的问题是 .. 部分视图在不同页面而不是在同一页面上打开。
      【解决方案3】:
      1. Onclickhtml 中的声明

        @item.CategoryName

      2. jQuery

        function projectlist(itemid) 
        
          $.ajax({
            url: "/Project/Projects"//url or controller with action
            type: "POST",
            data: { cid: itemid },
            dataType: "html",
            success: function (response) {
        
                $("#projectlist").html(response);//target div id
            },
            error: function () {
                alert("No Projects Found");
                $("#result").html('there is error while submit');
            }
          });
        }
        

      【讨论】:

        【解决方案4】:

        您的#btnclick 是一个submit 按钮。因此,当您单击它时,它将导致回发。这就是为什么您的整个页面都令人耳目一新。将其类型更改为button,这将停止刷新整个页面。

        -- 从这里忽略--

        其次,如果我理解正确的话,#viewlist 应该从一开始就隐藏起来。您可以通过将其设置为 display: none 来做到这一点,如下所示:

        <div id="viewlist" style="display: none'"> <%Html.RenderAction("MDLNoDataList"); %></div>
        

        然后,在您的 TestFun 中,当您需要像这样显示 #viewlist 时:

        function TestFun() {
          var mdlno = $("#ddlMDLNo").val();
          var txtmdlno = document.getElementById("Request_For_Id");
          txtmdlno.value = mdlno;
          //alert(txtmdlno.value);
        
          $('#viewlist').css('display', ''); // or something similar
        }
        

        -- 忽略到这里--

        我认为您的主要问题是您的按钮类型为submit

        更新:

        您不能使用$('#viewlist').load(...),因为返回部分视图的控制器方法标有[HttpPost]。请改用以下内容:

        $.ajax({
            url: "/Search/MDLNoDataList"
            type: "POST",
            data: {
                // NOTE : you will need to provide querystring items here
                // according to the properties in CRM_Doctor_Request so that
                // these parameters get bound to CRM_Doctor_Request by the 
                // DefaultModelBinder. If you paste the code for CRM_Doctor_Request
                // I can let you know what to put in here.
            },
            dataType: "html",
            success: function (response) {
              $("#viewlist").html(response);
            },
            error: function () {
              alert("No Projects Found");
              $("#viewlist").html('No results.');
          }
        });
        

        【讨论】:

        • 但是从 type="submit" 更改按钮 type=button 然后.. 没有记录显示。
        • 您可能需要使用 AJAX 技术自行调用以获取结果。我认为你应该看看使用 jQuery 的 AJAX 方法。您将使用类似$('#viewlist').load(...) 的方式将结果加载到#viewlist,如果加载成功,则通过$('#viewlist').css('display', '') 显示它;
        • 另一种方法可能是让#viewlist 始终可见,因此请跳过我的回答中关于使用display: none 样式隐藏和显示它的部分。首先在其中显示您的空结果网格,然后在#btnclick 的点击处理程序中加载#viewlist 中的新内容。
        • 您能否确认这一行 $("#btnclick").click(function () { $("#viewlist").load('/Search/MDLNoDataList.ascx') }); 已更改为 $("#btnclick").click(function () { $("#viewlist").load('/Search/MDLNoDataList') }); 并且该行位于像 $(function() { $("#btnclick").click(function () { $("#viewlist").load('/Search/MDLNoDataList') }); }); 这样的文档就绪处理程序中?
        • 我试过这个 $(function () { $("#btnclick").click(function () { $("#viewlist").load('/Search/MDLNoDataList') } ); });但问题是我按照您的建议使用按钮类型=按钮.. 按钮单击后视图正在加载,但数据未从数据库中显示。当我按下按钮 type="submit" 时,它的数据正在显示,但视图被加载到另一个页面而不是同一页面上。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多