【问题标题】:Asp.net Dropdownlist Page_Load isPostBack = FalseAsp.net Dropdownlist Page_Load isPostBack = False
【发布时间】:2013-09-18 13:12:12
【问题描述】:

我之前以类似的方式问过这个问题,这个问题仍然没有解决。我有一个由本地数据库填充的下拉列表。当用户选择一个选项时,页面刷新并且索引设置回第一个选项。发生这种情况时,SelectedIndexChanged 方法不会触发,在调试时,我发现在页面加载时,!isPostBack 始终为 true。

我为页面、下拉列表和数据库设置了 enableviewstate true。 以及页面的 AutoEventWireUp true。

请帮忙,我已经坚持这个问题大约一个星期了! 我觉得这个问题可能在我的母版页或 web.config 文件中仍然存在,所以我也发布这些问题

索引.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<BenchmarkApp.Models.Benchmark>>" AutoEventWireup="true" EnableViewState="true"%>

<!DOCTYPE html>

<script runat="server">

protected void Page_Load(object sender, EventArgs e)
{
    DropDownList1.SelectedIndexChanged += new EventHandler(DropDownList1_SelectedIndexChanged);  

    if (!this.IsPostBack)
    {
        Response.Write("Post Back is False");
        bindData();
    }
}

protected void bindData()
{
    DropDownList1.Items.Clear();
    DropDownList1.DataSourceID = "SqlDataSource1";
    DropDownList1.DataTextField = "Version";
    DropDownList1.DataValueField = "Id";
    DropDownList1.DataBind();
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    Response.Write((sender as DropDownList).SelectedItem.Text);
    Label1.Text = DropDownList1.SelectedItem.Text;
}

</script>

<html>

<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Benchmark</title>
</head>

<body>

  <form id="bmform" runat="server">

<p>
    <%: Html.ActionLink("Create New", "Create") %>
</p>
<table border="1">
    <tr>
        <th>
            Build version:
        </th>
        <th>
            <%-- Html.DropDownList("Builds", null, new {@onchange = "onChange(this.value);" }) --%>
            <%-- Html.DropDownList("BuildID", (SelectList) ViewBag.Builds, "--Select One--") --%>
            <%-- Html.DropDownList("BuildDD", (IEnumerable<SelectListItem>)ViewBag.Builds, "--Select One--") --%>

            <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
                DataSourceID="SqlDataSource1" DataTextField="Version"
                onselectedindexchanged="DropDownList1_SelectedIndexChanged" 
                DataValueField="Id">
            </asp:DropDownList>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                ConnectionString="<%$ ConnectionStrings:DAContext %>" 
                SelectCommand="SELECT [Id], [Version] FROM [Builds]"></asp:SqlDataSource>
        </th>
        <th>
            <asp:Label ID="Label1" runat="server" Text= "--Build Version--"></asp:Label>
        </th>
    </tr>
</table>

<table border="1">
    <tr>
        <th>
            <%: Html.DisplayNameFor(model => model.Script.Name) %>
        </th>
        <th>
            <%: Html.DisplayNameFor(model => model.Build.Version) %>
        </th>
        <th>
            <%: Html.DisplayNameFor(model => model.MinTime) %>
        </th>
        <th>
            <%: Html.DisplayNameFor(model => model.MeanTime) %>
        </th>
        <th>
            <%: Html.DisplayNameFor(model => model.MaxTime) %>
        </th>
        <th>
        </th>
    </tr>
    <% foreach (var item in Model)
       { %>
    <tr>
        <td>
            <%: Html.DisplayFor(modelItem => item.Script.Name) %>
        </td>
        <td>
            <%: Html.DisplayFor(modelItem => item.Build.Version) %>
        </td>
        <td>
            <%: Html.DisplayFor(modelItem => item.MinTime) %>
        </td>
        <td>
            <%: Html.DisplayFor(modelItem => item.MeanTime) %>
        </td>
        <td>
            <%: Html.DisplayFor(modelItem => item.MaxTime) %>
        </td>
        <td>
            <%: Html.ActionLink("Edit", "Edit", new { id=item.BenchmarkID }) %>
            |
            <%: Html.ActionLink("Details", "Details", new { id=item.BenchmarkID }) %>
            |
            <%: Html.ActionLink("Delete", "Delete", new { id=item.BenchmarkID }) %>
        </td>
    </tr>
    <% } %>
</table>

  </form>

</body>
</html>

大师

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" AutoEventWireup="true" EnableViewState="true" %>
<!DOCTYPE html>
<html lang="en">
    <head runat="server">
        <meta charset="utf-8" />
        <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="<%: Url.Content("~/favicon.ico") %>" rel="shortcut icon" type="image/x-icon" />
    <meta name="viewport" content="width=device-width" />
    <%: Styles.Render("~/Content/css") %>
    <%: Scripts.Render("~/bundles/modernizr") %>
</head>
<body>

<form id="master" runat="server">

    <header>
        <div class="content-wrapper">
            <div class="float-left">
                <p class="site-title"><%: Html.ActionLink("your logo here", "Index", "Home") %></p>
            </div>
            <div class="float-right">
                <section id="login">
                    <%: Html.Partial("_LoginPartial") %>
                </section>
                <nav>
                    <ul id="menu">
                        <li><%: Html.ActionLink("Home", "Index", "Home") %></li>
                        <li><%: Html.ActionLink("About", "About", "Home") %></li>
                        <li><%: Html.ActionLink("Contact", "Contact", "Home") %></li>
                    </ul>
                </nav>
            </div>
        </div>
    </header>
    <div id="body">
        <asp:ContentPlaceHolder ID="FeaturedContent" runat="server" />
        <section class="content-wrapper main-content clear-fix">
            <asp:ContentPlaceHolder ID="MainContent" runat="server" />
        </section>
    </div>
    <footer>
        <div class="content-wrapper">
            <div class="float-left">
                <p>&copy; <%: DateTime.Now.Year %> - My ASP.NET MVC Application</p>
            </div>
        </div>
    </footer>

    <%: Scripts.Render("~/bundles/jquery") %>
    <asp:ContentPlaceHolder ID="ScriptsSection" runat="server" />

    </form>

</body>
</html>

Web.config

<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor"  type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
  <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
  <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
  </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
<add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.web>
    <httpHandlers>
  <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>

<!--
    Enabling request validation in view pages would cause validation to occur
    after the input has already been processed by the controller. By default
    MVC performs request validation before a controller processes the input.
    To change this behavior apply the ValidateInputAttribute to a
    controller or action.
-->
    <pages
        validateRequest="false"
    pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
  <controls>
    <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
  </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
  <remove name="BlockViewHandler"/>
  <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
  </system.webServer>
</configuration>

非常感谢您!

【问题讨论】:

  • 为什么要混合 MVC 和 WebForms?
  • 请不要因为没有得到答案就转发the same question。随意使用该问题上的“编辑”链接,使用您获得的任何新信息对其进行更新。

标签: asp.net asp.net-mvc asp.net-mvc-4 drop-down-menu postback


【解决方案1】:

如上所述,您无法在 MVC 应用程序中使用 asp 控件。 (好吧,它对我不起作用)。相反,我将我的应用程序切换为使用 Razor 引擎并在 View.cshtml 中输入:

 @using (Html.BeginForm("FilterBenchmarks", "Benchmark", FormMethod.Post))
{

<table border="1">
    <tr>
        <th>
            Build version:
        </th>
        <th>
            @Html.DropDownList("BuildID", (SelectList) ViewBag.Builds, "--Select One--", new {@onchange = "this.form.submit()"})
        </th>
    </tr>
</table>

在控制器页面中:

        [HttpPost]
    public ActionResult FilterBenchmarks(FormCollection form)
    {
        var buildId = Convert.ToInt32(form["BuildID"]);
        var benchmarks = db.Benchmarks.Where(b => b.BuildID == buildId).Include(b => b.Build).Include(b => b.Script);

        var query = db.Builds.Select(c => new { c.Id, c.Version });
        ViewBag.Builds = new SelectList(query.AsEnumerable(), "Id", "Version");

        return View("Index", benchmarks.ToList());
    }

这确实对我有用,现在一切正常!我要感谢提出各种解决方案的人,他们让我重新思考这个场景! 谢谢!

【讨论】:

    【解决方案2】:

    使用所提供的代码,很难复制您遇到的确切问题。但是,几个简单的步骤应该可以解决这个问题。

    首先,在Page_Load() 中,您正在运行bindData 以将下拉列表链接到数据。但是,您的下拉列表已经链接到它:

     <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
                DataSourceID="SqlDataSource1" DataTextField="Version"
                onselectedindexchanged="DropDownList1_SelectedIndexChanged" 
                DataValueField="Id">
    

    我建议从标签中删除DataSourceDataValueField 等属性,因为它们是多余的。

    其次,如前所述,您正在Page_Load() 中执行绑定。某些过程 - 包括设置当前选定的项目 - 发生在 Page_Init() 完成和 Page_Load() 开始之间,因此您可能会发现将您的呼叫转移到 bindData()Page_Init() 也可以。

    最后,您的Page_Load() 开头为:

    DropDownList1.SelectedIndexChanged += 
                           new EventHandler(DropDownList1_SelectedIndexChanged);  
    

    但是您的标签已经包含onselectedindexchanged 属性,因此您可能最终会运行DropDownList_SelectedIndexChanged() 两次。删除其中一个以提高效率。

    【讨论】:

    • OP 正在使用 MVC 并尝试使用 asp 控件。
    • 感谢您快速回复我的问题!非常感激!我已经尝试了你建议的一切,但仍然没有运气。我理解很难复制这种情况。这就是我无法解决问题的原因,我根本没有使用过asp.net,我觉得问题不在我的代码中,而在其他地方。也许是我的设置,或者某种配置。
    • @afzalulh 我意识到,是的。我只是不相信这是他的问题 - 将两者混合是可能的。
    • 不,这种混合是不可能的。
    • @afzalulh 我已经设法在 MVC4 站点中编写了一个测试 ASPX 页面,类似于 OP 编写的页面(但是,工作!);见stackoverflow.com/questions/7288840/…
    猜你喜欢
    • 1970-01-01
    • 2012-11-19
    • 2011-09-30
    • 2011-07-22
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多