0

ドロップダウンリスト、ラジオボタン、チェックボックス、テキストボックスなどのビューコントロールにデータを保持しながら、検証失敗メッセージで同じビューを再度表示したいと考えています。データは、ViewData を使用してドロップダウン リストにバインドされます。viewdata を使用したチェック ボックスのデータ バインド。ユーザーは、テキストボックスとチェックボックス コントロールに値を入力します。ビューが検証メッセージとともに表示されると、コントロールがリセットされ、ビューを表示する前にドロップダウン リストのデータを viewData に渡す必要があります。これに対する解決策を教えてください。

よろしくお願いします、ツァラ。

4

1 に答える 1

0

以下の必要なコードを見つけてください 以下の View を見つけてください。ドロップダウン リストとチェック ボックスにいくつかのデータがあります。初めてのページ レンダリングでは、ViewData で渡されます。

<div id="RegisterLogin">
<label id="Label1"> Project:</label>
              <%= Html.Label( Convert.ToString(ViewData["SelectedProject"])) %>
              <%= Html.DropDownList("ProjectCode", (SelectList)ViewData["ddlProject"], "--Select--", new { id = "ddlProject" , title = "Select Project" })%>

            <br />
            <br />

            <label id="Label2">
                Select User:</label>

             <%= Html.DropDownList("ddlUsers", (SelectList)ViewData["ddlUsers"], "--Select User--", new { id = "ddlUsers", title = "Select User" })%>
            <br />
            <br />
            <label id="spacing">
                Username:</label>
            <input type="text" name="txtUserName" title="Enter username" id="txtUserName" />
             <%= Html.ValidationMessage("username") %>
            <br />
            <br />
            <label id="leftalign">
               Password :</label>
            <input type="password" name="txtPassword" title="Enter your password" id="txtPassword" />
                                <%= Html.ValidationMessage("password") %>
            <br />

            <br />
            Confirm Password :
            <input type="password" name="txtConfirmPassword" title="Confirm your password" id="txtConfirmPassword" />
            <%= Html.ValidationMessage("confirmPassword") %>
            <br />
            <br />
            <label id="space" >Email :</label>
            <input type="text" name="txtEmailId" title="Enter your email id" id="txtEmailId" />
            <%= Html.ValidationMessage("email") %>
            <br />
            <br />

          <label id="rolealign"> Assign Role : </label>
            <div class="listPermissions">
            <%= Html.ValidationMessage("role") %>
                <% Dictionary<string, string> lstRoles = ViewData["ListRoles"] as Dictionary<string, string>; %>
                <% if (lstRoles != null)
                   {
                       int iCounter = 1;
                       foreach (KeyValuePair<String,String> item in lstRoles)
                       { %>
                       <%= Html.CheckBoxCustom(Convert.ToString(iCounter+1), "chkRole", item.Value,"") %>
                       <%= Html.Encode(item.Key) %><br />

                <%}
                   }%>

            </div>

            <br />
            <input type="image" src="../../Content/save.jpg" value="Save" alt="Save" style="padding-left:250px;"/>
            <%--<img src="../../Content/save.jpg" alt="Save" id="imageGO"  />--%>
            <img src="../../Content/reset.jpg" onclick="document.forms[0].reset()" alt="Reset"/> 
            <%--<img src="../../Content/reset.jpg" alt="Reset" onclick="return btnCancel_onclick()" />--%>
        </div>

ポストバック関数呼び出しの検証では、次のように行われます

public ActionResult Register(文字列 txtUserName、文字列 txtPassword、文字列 txtConfirmPassword、文字列 txtEmailId、FormCollection frmCollection)

{ string strValue = frmCollection.Get("chkRole"); ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

        if (ValidateRegistration(txtUserName, txtEmailId, txtPassword, txtConfirmPassword, frmCollection))
        {
            if (strValue == "")
            {
                ModelState.AddModelError("role", "Please select the role");
            }
            else
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(txtUserName, txtPassword, txtEmailId);


                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuth.SignIn(txtUserName, false /* createPersistentCookie */);

                    // Create an empty Profile for the newly created user



                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
                }
            }
        }

        //IDictionary<string, ValueProviderResult> valueProvider = frmCollection.ToValueProvider();
        //Dictionary<string, string> valueProvider = frmCollection.AllKeys.ToDictionary(k => k, v => frmCollection[v]);
        //foreach (string i in valueProvider.Keys)
        //{
        //    ModelState.SetModelValue(i, valueProvider[i]);
        //} 

        //Get list of projects
        ProjectOperations objProjectOperations = new ProjectOperations();
        List<Project> lstProjects = objProjectOperations.GetAll();

        //Logging://Verbose:
        logEntry = new LogEntry("List of project added into view data", "AzureTableLogs", 0, 0, System.Diagnostics.TraceEventType.Verbose, "", null);
        Logger.Write(logEntry);

        ViewData["ddlProject"] = new SelectList(lstProjects, "ProjectCode", "ProjectName");

        MembershipUserCollection lstUser = Membership.GetAllUsers();

        ViewData["ddlUsers"] = new SelectList(lstUser, "UserName", "UserName");

        //MembershipUserCollection lstUser= Membership.GetAllUsers();
        // If we got this far, something failed, redisplay form
        return View();
    }

ビューを表示する前に毎回、ビュー データに値が必要です。

これを解決するために、IDictionary valueProvider = frmCollection.ToValueProvider(); のような解決策を試しました。ただし、mvc 2.0 ではサポートされていません。

詳細が必要な場合は、お知らせください。

于 2010-07-26T09:25:05.553 に答える