Как сформировать, отправить и показать другую страницу в ASP.Net MVC? - PullRequest
0 голосов
/ 08 апреля 2010

Я новичок в asp.net mvc ..

поэтому я просто создаю двухстраничное приложение, которое берет регистрационную информацию пользователя и публикует ее в базе данных.

Я использую множество вызовов jquery и ajax для извлечения данных из базы данных, используя хранимый объект proc из linq to sql.

и в настоящее время я застрял на одной странице, где после того, как пользователь отправляет форму, он должен перенаправить его на /Home/ProductAdded.

То, что я нашел, было ошибкой:

 Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

то, что использовалось в моей форме, это в основном комбинация элементов управления html, элементов управления asp.net и некоторых элементов управления asp.net mvc.

Я отправляю форму, используя action = "/ Home / ProductAdded" и после некоторого поиска в Google я обнаружил, что должен был добавить ключ машины, но после этого страница индекса становится недоступной для просмотра. потому что он не может найти индексный файл сейчас.

удаление действия помогает, но теперь оно просто никуда не денется. так чего мне здесь не хватает?

Я чувствую, что мне не хватает многих базовых знаний об asp.net mvc, и я даже не знаю, как отправить форму и перейти на другую страницу здесь !!

Редактировать: включены мои index.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page</asp:Content>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">

    <script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.jsonSuggest.js" type="text/javascript"></script>
    <script src="Scripts/ProductRegistration.js" type="text/javascript"></script>
    <script src="Scripts/jquery.Guid.js" type="text/javascript"></script>

    <script src="Scripts/jquery.scrollTo-min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.ui.core.min.js" type="text/javascript"></script>

    <script src="Scripts/jquery.ui.datepicker.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.ui.widget.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.colorbox-min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.validate.min.js" type="text/javascript"></script>
    <script src="Scripts/date.js" type="text/javascript"></script>

    <form id="frmProductReg" runat="server" class="frmProductReg" action="/Home/ProductAdded">
        <asp:Panel ID="BreadCrumbPanel" runat="server" HorizontalAlign="Left" CssClass="breadcrumbCentered">
            Register Your Product</asp:Panel>
        <asp:Panel ID="MainContentPanel" runat="server"
            HorizontalAlign="Left" CssClass="headerCentered">
            <!-- Grab the country name via the geo locator -->
            <h1>Two-Step Online Product Registration</h1>
            we detect that you&#39;re located in 
            <!-- using span as it can auto resize and keeping the input for form submission later -->
            <span id="geoLocatedCountry" class="selectedCountry" ><%= Html.Encode(ViewData["CountryName"]) %></span>
            To change your country or region, please
            <span id="changeCountryUpper">click here</span>
            .
            <br /><br />
            <h3>Step 1: Enter your product information</h3>
        </asp:Panel>
        <asp:Panel ID="Panel3" runat="server" CssClass="contentCentered" HorizontalAlign="Left">

            <h3 align="left">Method 1</h3>
            Key in the name of your product in the space below. Choose the most appropriate 
            if there are a few similar ones, then click
            <img id="Image1" src="Images/btn_addButtonS.gif" alt="Add Button"/>
            <br />
            You can register multiple products by repeating this step.
            <table id="Table1">
                <tr>
                    <td>
                    <input type="text" id="tboProductCount" class="tboProductCount" value="0" />
                    <input type="text" id="tboAddProductId" class="tboAddProductId" />
                    <input id="tboAddProduct" class="tboAddProduct" />
                    </td>
                    <td>
                    <input type="image" id="btnAddProduct" class="btnAddProduct" src="Images/btn_addButton.gif" />
                    </td>
                </tr>
            </table>
            <br />
            <h3 align="left">
                Method 2</h3>
            Select the product(s) you wish to register and click
            <asp:Image ID="Image2" runat="server" ImageUrl="~/Images/btn_addButtonS.gif" />. 
            You can register multiple products by repeating this step. To remove
            <br />
            any product, click on the Remove button<asp:Image ID="Image3" runat="server" ImageUrl="~/Images/btn_remove.gif" />
            .<br />
            <br />
            <table border="0" cellpadding="2" cellspacing="0" frame="void" 
                style="width: 100%">
                <tr>
                    <td style="width: 238px">
                        <asp:ListBox ID="ListBox1" CssClass="LBox1" runat="server" Width="100%"></asp:ListBox>
                    </td>
                    <td style="width: 239px">
                        <asp:ListBox ID="ListBox2" CssClass="LBox2" runat="server" Width="100%"></asp:ListBox>
                    </td>
                    <td style="width: 290px">
                        <asp:ListBox ID="ListBox3" CssClass="LBox3" runat="server" Width="100%"></asp:ListBox>
                    </td>
                </tr>
                <tr>
                    <td style="width: 238px">
                        &nbsp;</td>
                    <td style="width: 239px">
                        &nbsp;</td>
                    <td style="width: 290px">
                        <asp:ImageButton ID="btnAddProduct2" cssClass="btnAddProduct2" runat="server" Height="26px" 
                            ImageAlign="Right" ImageUrl="~/Images/btn_addButton.gif" />
                    </td>
                </tr>
            </table>
            <br />
       </asp:Panel>
       <asp:Panel ID="PanelProductReg" runat="server" CssClass="PanelProductReg" HorizontalAlign="Left">
            <table id="ProductRegistrationTable" class="ProductRegistrationTable">
                <tr style="font-weight:bold;">
                    <td class="productIdCol">Product Id</td>
                    <td style="width:30%">Product</td>
                    <td style="width:30%">Serial Number<span class="redWarning">*</span> (
                    <a id="anchorSerialNoHelp" href="http://www.yahoo.com">What's this</a>)</td>
                    <td style="width:5%"><!-- used for the serial number help image button--></td>
                    <td style="width:20%">Date of Purchase<span class="redWarning">*</span></td>
                    <td>Remove</td>
                </tr>
            </table>
        </asp:Panel>
        <asp:Panel ID="Panel4" runat="server" HorizontalAlign="Left" CssClass="headerCentered">
            <h3>Step 2: Enter your personal details</h3>          
        </asp:Panel>
        <asp:Panel ID="Panel1" runat="server" CssClass="contentCentered" HorizontalAlign="Left">
            <table style="width: 97%">
                <tr>
                    <td style="width: 243px">
                        First Name<span class="redWarning">*</span>:</td>
                    <td>
                        <%= Html.TextBox("Customer.FirstName") %>
                        <!--asp:TextBox ID="customer.FirstName" ></asp:TextBox-->
                    </td>
                </tr>
                <tr>
                    <td style="width: 243px; height: 18px">
                        Last Name<span class="redWarning">*</span>:</td>
                    <td style="height: 18px">
                        <%= Html.TextBox("Customer.LastName") %>
                        <!-- asp:TextBox ID="customer.LastName" ></asp:TextBox -->
                    </td>
                </tr>
                <tr>
                    <td style="width: 243px">
                        Email Address<span class="redWarning">*</span>:</td>
                    <td>
                        <%= Html.TextBox("Customer.Email") %>
                        <!--asp:TextBox ID="customer.Email" ></asp:TextBox-->
                    </td>
                </tr>
                <tr>
                    <td style="width: 243px">
                        Re-enter Email Address<span class="redWarning">*</span>:</td>
                    <td>
                        <input type="text" id="tboConfirmEmail" />
                    </td>
                </tr>
                <tr>
                    <td style="width: 243px">
                        Country/Region<span class="redWarning">*</span>:</td>
                    <td>
                        <!-- hiding the input as i can't auto resize it and i still need this
                        data when i submit the form -->
                        <span id="selectedCountry" class="selectedCountry" ><%= ViewData["CountryName"] %>
                        </span>
                        <input type="hidden" id="customer.CountryID" value="65"/>
                        <input type="hidden" id="txtSelectedCountry" value="<%= Html.Encode(ViewData["CountryName"]) %>" />
                        <span id="currentCountry"> (Change this?)
                        </span>
                        <span id="changeCountry"> 
                        <%= Html.DropDownList("countries")%>
                        </span>
                    </td>
                </tr>
                <tr id="stateNameRow">
                    <td style="width: 243px">
                        State/Province:</td>
                    <td>
                        <!--%= Html.DropDownList("stateDdl") %-->
                        <asp:DropDownList ID="stateDdl" runat="server" CssClass="stateDdl"></asp:DropDownList>
                        &nbsp;&nbsp;&nbsp;&nbsp; or&nbsp;&nbsp;
                        <%= Html.TextBox("Customer.StateName")%>
                        <!--asp:TextBox ID="customer.StateName"></asp:TextBox-->
                    </td>
                </tr>
                <tr>
                    <td style="width: 243px">
                        Gender:</td>
                    <td>
                        <%= Html.RadioButton("Customer.Male", "Male",true)%> Male
                        <%= Html.RadioButton("Customer.Female", "Female")%> Female
                        <!--asp:RadioButton ID="rbtMale" Text="Male" Checked="True" 
                            GroupName="rboGender" />
                        &nbsp;&nbsp;&nbsp;
                        <asp:RadioButton ID="rbtFemale"  Text="Female" 
                            GroupName="rboGender" /-->
                    </td>
                </tr>
                <tr>
                    <td style="width: 243px">
                        Date of Birth:</td>
                    <td>
                        <input type="text" id="Customer_DOB" name="Customer.DOB" class="dobPicker" />
                    </td>
                </tr>
                <tr>
                    <td style="width: 243px">
                        &nbsp;</td>
                    <td>
                        <%= Html.CheckBox("Customer.Subscribe",true) %>
                        <!--asp:CheckBox ID="cboNewsletter" Checked="True" / -->
                        &nbsp;I would like to receive newsletters for the latest Creative products, special 
                        offers and events.
                    </td>
                </tr>
                <tr>
                    <td style="width: 243px">
                        &nbsp;</td>
                    <td>
                        * Denotes mandatory field.</td>
                </tr>
                <tr>
                    <td style="width: 243px">
                        &nbsp;</td>
                    <td>
                        <!--asp:ImageButton ID="ImageButton1"
                            ImageUrl="~/Images/btn_submit.gif" /-->
                        <input type="image" id="imgbtnSubmit" src="Images/btn_submit.gif"/>    
                        <input type="image" id="imgbtnClear" src="Images/btn_clear.gif"/>
                    </td>
                </tr>
            </table>

        </asp:Panel>
    </form>
</asp:Content>

Ответы [ 3 ]

1 голос
/ 08 апреля 2010

В методе, которым вы обрабатываете запрос, вы можете вернуть Redirect (url); Это должно решить вашу непосредственную проблему.

Другая вещь, от которой вам следует избегать, - это использование элементов управления asp.net. Вам не нужны они в MVC. Если вы их используете, не используйте их с viewstate, потому что MVC не делает ничего с вашим элементом Form, как веб-формы, которые заставляют ViewState работать.

1 голос
/ 08 апреля 2010

Короче говоря, вы не должны использовать серверные элементы управления ASP.NET, которые используют viewstate в MVC - ASP.NET MVC не поддерживает viewstate. Любые элементы управления, которые полагаются на viewstate, не будут работать - и даже те, которые не соответствуют философии MVC.

1 голос
/ 08 апреля 2010

Шаблон Post-Redirect-Get - это ответ на ваш вопрос. Ищите SO или Google, и вы должны найти много информации об этом.

Также вы упоминаете элементы управления ASP.NET? Они не должны присутствовать на страницах ASP.NET MVC View, поскольку они несовместимы с MVC.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...