点击按钮加载部分视图

4

这个问题可能已经被重复了,但我有些问题。我在页面中有一个下拉列表和搜索按钮。在下拉列表的更改事件中,将视图绑定到模型上。当单击搜索按钮时,选择的值将根据记录列表显示在部分视图中。如下所示,所有操作都已正确完成:

<%@ 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));
        }
4个回答

2
我已经将所有的建议片段编译成了我认为可以满足您需求的标记语言。如下所示。
请注意,我只是在记事本中输入了这些内容,因此可能会有语法错误,但是策略应该能够帮助您达到所需目的。
我们正在尝试使用 AJAX 技术,因此我们不想提交表单,因为那会导致整个页面刷新,所以提交按钮必须变成普通按钮。
因此我们的策略是:
- 渲染主表单元素并 - 处理以下内容之一: - 按钮单击事件或 - 下拉列表更改事件-- 在这种情况下,我们必须完全省略按钮。
如果我们想要仅在单击按钮后更新结果,则:
当单击按钮时,我们获取包含结果网格的局部视图,并使用局部视图的 HTML 替换 #viewlist 的整个内部 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>

1

脚本

<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>

将HtmlBegin表单的选项添加到HtmlBeginForm表单中,如下所示:
<% 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标签中没有显示任何内容。 - IT_INFOhUb
这段代码可以工作,但现在的问题是...部分视图在不同页面上打开,而不是在同一页面上。 - IT_INFOhUb

1
  1. HTML中的Onclick语句

    @item.CategoryName

  2. Jquery

    function projectlist(itemid) 
    
      $.ajax({
        url: "/Project/Projects",//url或controller和action
        type: "POST",
        data: { cid: itemid },
        dataType: "html",
        success: function (response) {
    
            $("#projectlist").html(response);//目标div的ID
        },
        error: function () {
            alert("未找到项目");
            $("#result").html('提交时出现错误');
        }
      });
    }
    

1
您的#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时,没有记录被显示。 - IT_INFOhUb
你可能需要使用 AJAX 技术自己调用来获取结果。我认为你应该考虑使用 jQuery 的 AJAX 方法。你将通过类似 $('#viewlist').load(...) 的方式加载结果到 #viewlist 中,如果加载成功,则通过 $('#viewlist').css('display', '') 显示它。 - Umar Farooq Khawaja
另一种方法可能是始终将#viewlist保持可见,因此可以跳过我的答案中有关使用display: none样式隐藏和显示它的部分。首先,在其中显示空的结果网格,并在单击#btnclick处理程序中加载#viewlist中的新内容。 - Umar Farooq Khawaja
你能确认这行代码 $("#btnclick").click(function () { $("#viewlist").load('/Search/MDLNoDataList.ascx') }); 已经被修改成 $("#btnclick").click(function () { $("#viewlist").load('/Search/MDLNoDataList') }); 并且这行代码在文档准备好的处理程序中,像这样 $(function() { $("#btnclick").click(function () { $("#viewlist").load('/Search/MDLNoDataList') }); }); 吗? - Umar Farooq Khawaja
我尝试了以下代码:$(function () { $("#btnclick").click(function () { $("#viewlist").load('/Search/MDLNoDataList') }); }); 但问题是,我按照您的建议将按钮类型设置为button,点击按钮后视图会加载,但是数据并没有从数据库中显示。当我将按钮类型设置为“submit”时,数据可以显示,但是视图会在另一页中加载,而不是在同一页中加载。 - IT_INFOhUb
我在视图的代码中做了一些更改,但仍然遇到了同样的问题。请提供建议,谢谢。 - IT_INFOhUb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接