在 Asp.net 2.0 中,如何在视图中的控件中保留数据,同时重新显示带有验证错误消息的同一视图

发布于 2024-09-11 01:56:18 字数 218 浏览 1 评论 0原文

我想保留视图控件中的数据,例如下拉列表、单选按钮、复选框、文本框,同时再次显示相同的视图并显示验证失败消息。数据位于使用 ViewData 绑定的下拉列表中。使用 viewdata 进行复选框数据绑定。用户在文本框和复选框控件中输入值。 当显示带有验证消息的视图时,控件将被重置,并且下拉列表数据需要在显示视图之前在 viewData 中传递。请让我知道对此的任何解决方案。

谢谢&问候, 察拉。

I want to retain data in the view controls like drop down list, radio button, checkbox, textbox while displaying same view again with validation fail message. Data is in the drop down list bind using the ViewData. Check box data bind using viewdata. User enter values in the textbox and for checkbox control.
When view is displayed with the validation messages controls are reset and for drop down list data needs to be passed in the viewData before displaying view. Please let me know any solution to this.

Thanks & Regards,
Tsara.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

じее 2024-09-18 01:56:18

在下面找到所需的代码
请在下面查看。下拉列表和复选框中都有一些数据。第一次页面渲染时,它会在 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(string txtUserName, string txtPassword, string txtConfirmPassword, string txtEmailId, FormCollection frmCollection)

{
字符串 strValue = frmCollection.Get("chkRole");
ViewData["密码长度"] = 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中不支持。

如果您需要更多详细信息,请告诉我。

Find the required code below
Please find below View . There is some data in the drop down list and also in the check box. For the first time page render it is passed in the 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>

In postback function call validation is done as follows

public ActionResult Register(string txtUserName, string txtPassword, string txtConfirmPassword, string 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();
    }

Every time before displaying view need to have values in the view data.

For resolve this i tried solution i got like
IDictionary valueProvider = frmCollection.ToValueProvider();
but it is not supported in mvc 2.0.

If you need more details please let me know.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文