在按钮单击上加载部分视图

时间:2013-02-13 07:08:36

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

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

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

enter image description here

enter image description here

一切正常但是..在点击搜索按钮之前显示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 个答案:

答案 0 :(得分:2)

我已经将我的所有建议片段编译成了标记,我认为它会为您提供所需的内容。它如下。

请记住,我刚刚在记事本中输入了这个内容,因此它可能会出现语法错误,但该策略应该可以让您找到所需的位置。

注意:我们正在尝试使用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>

答案 1 :(得分: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>

将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" />    
<% } %> 

答案 2 :(得分:1)

    html中的
  1. Onclick语句

    @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');
        }
      });
    }
    

答案 3 :(得分:1)

您的#btnclicksubmit按钮。因此,当您单击它时,它将导致回发。这就是整个页面令人耳目一新的原因。将其类型更改为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.');
  }
});