开发者

In Asp.net 2.0 how to retain data in the controls in view while redisplaying same view with the validation error message

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜