0

I've asked this question before in a similar manner, the the question still remains unsolved. I have a dropdownlist, populated by a local database. When a users selects an option, the page refresh and the index is set back to the first option. When this happens the SelectedIndexChanged method does not fire, when debugging, I have found that on the page load, !isPostBack is always true.

I have enableviewstate true for the page, dropdownlist and for the database as well. along with AutoEventWireUp true for the page.

Please help, I've been stick on this one problem for about a week now! I feel the problem may persist in my master page or the web.config file, so ill post those as well

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

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

Thank you very much in advance!!

4

2 回答 2

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());
    }

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

于 2013-09-19T13:32:59.043 回答
-1

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

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

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

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

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

最后,您的Page_Load()开始是:

DropDownList1.SelectedIndexChanged += 
                       new EventHandler(DropDownList1_SelectedIndexChanged);  

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

于 2013-09-18T13:43:57.727 回答