Results 1 to 5 of 5

Thread: MVC1 - Invalid Values persist on form and Model

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Sep 2008
    Location
    Jacksonville, Florida
    Posts
    147

    MVC1 - Invalid Values persist on form and Model

    A user submits registration information to the form:

    Code:
    <h2>Create</h2>
    
    <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
    
    <% using (Html.BeginForm()) {%>
    
        <fieldset>
            <legend>Fields</legend>
            <p>
                <label for="Nbk">Nbk:</label>
                <%= Html.TextBox("Nbk",null, new  {Disabled="Disabled" })%>
                <%= Html.ValidationMessage("Nbk", "*") %>
            </p>
            <p>
                <label for="Name">Name:</label>
                <%= Html.TextBox("Name") %>
                <%= Html.ValidationMessage("Name", "*") %>
            </p>
            <p>
                <label for="Email">Email:</label>
                <%= Html.TextBox("Email") %>
                <%= Html.ValidationMessage("Email", "*") %>
            </p>
            <p>
                <label for="MailCode">MailCode:</label>
                <%= Html.TextBox("MailCode") %>
                <%= Html.ValidationMessage("MailCode", "*") %>
            </p>
            <p>
                <label for="TelephoneNumber">TelephoneNumber:</label>
                <%= Html.TextBox("TelephoneNumber") %>
                <%= Html.ValidationMessage("TelephoneNumber", "*") %>
            </p>
            <p>
                <label for="OrganizationId">OrganizationId:</label>
                <%= Html.TextBox("OrganizationId") %>
                <%= Html.ValidationMessage("OrganizationId", "*") %>
            </p>
            <p>
                <label for="OrganizationSponsorId">OrganizationSponsorId:</label>
                <%= Html.TextBox("OrganizationSponsorId") %>
                <%= Html.ValidationMessage("OrganizationSponsorId", "*") %>
            </p>
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    
    <% } %>
    Controller:

    Code:
    [Authorize]
            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Create(DefectSeverityAssessmentBusiness.ModelRegistration registration)
            {
                    registration.Nbk = StateController.GetNbk(Request);
                    try
                    {
                            var errors = DataAnnotationsValidationRunner.GetErrors(registration);
                            if (errors.Any())
                                    foreach (var item in errors)
                                    {
                                            if( ModelState[item.PropertyName].Errors.Count==0)
                                            ModelState.AddModelError(item.PropertyName, item.ErrorMessage);
                                            //ModelState.SetModelValue(item.PropertyName,ViewData[item.PropertyName].ToValueProvider());
                                    }
                            if (ModelState.IsValid)
                            {
                                    _RegistrationRepository.CreateRegistration(registration);
                                    return RedirectToAction("Index", "Assessment");
                            }
                    }
                    catch (Exception exception)
                    {
                            ModelState.AddModelError("Exception", exception);
                    }
    
    
                    return View();
    
            }
    controller factory:

    Code:
    ControllerBuilder.Current.SetControllerFactory(new Models.InMemoryRepositories.InMemoryControllerFactory());
    
    public class InMemoryControllerFactory : IControllerFactory
    {
    
            private readonly Dictionary<string, IController> _controllers = new Dictionary<string, IController>();
    
            private readonly Dictionary<string, Func<IController>> _controllerFactoryDictionary =
                    new Dictionary<string, Func<IController>>();
    
            public InMemoryControllerFactory()
            {
                    InitializeDictionary();
            }
    
            private void InitializeDictionary()
            {
    
                    AddFactory(typeof(Controllers.HomeController), () => new Controllers.HomeController(
                            new Models.InMemoryRepositories.Registration.InMemoryRegistrationRepository()));
                    AddFactory(typeof(Controllers.RegistrationController),() => new Controllers.RegistrationController(
                               new Models.InMemoryRepositories.Registration.InMemoryRegistrationRepository()));
                    AddFactory(typeof(Controllers.AssessmentController),()=> new Controllers.AssessmentController(
                            new Models.InMemoryRepositories.Registration.InMemoryDefectRepository(),
                            new Models.InMemoryRepositories.Registration.InMemoryAssessmentRepository())
                            );
            }
    
            private void AddFactory(Type type, Func<IController> creator)
            {
            const string Str_Controller = "Controller";
                                    var fullname = type.Name;
                                    Debug.Assert(fullname.EndsWith(Str_Controller));
                                    var controllerName= fullname.Substring(0, fullname.Length - Str_Controller.Length);
    
                    Func<string, Func<IController>> controllerFactoryFunc = (_controllerName) =>
                            {
                                    return () =>
                                            {
                                                    //var controllerName=ControllerNameFunc(type);
                                                    if (!_controllers.ContainsKey(_controllerName))
                                                            _controllers.Add(_controllerName, creator());
                                                    return _controllers[_controllerName];
                                            };
                            };
    
                    _controllerFactoryDictionary.Add(controllerName, controllerFactoryFunc(controllerName));
            }
    
    
            #region IControllerFactory Members
    
    
    
            public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
            {
                    return _controllerFactoryDictionary[controllerName]();
            }
    
            /// <summary>
            /// Code via http://nayyeri.net/custom-controller-factory-in-asp-net-mvc
            /// </summary>
            /// <param name="controller"></param>
            public void ReleaseController(IController controller)
            {
    
                    if (controller is IDisposable)
                            (controller as IDisposable).Dispose();
                    else
                            controller = null;
            }
    
            #endregion
    }
    Through the controller with an invalid value at first, then a valid one, but the error message stays and modelstate stays invalid. Why does this happen? i'm using the default model binder, but the included controller factory.
    vb.net and C# in 2008 .net 3.5
    ImaginaryDevelopment blog

  2. #2
    PowerPoster gep13's Avatar
    Join Date
    Nov 2004
    Location
    The Granite City
    Posts
    21,963

    Re: MVC1 - Invalid Values persist on form and Model

    Hey,

    What is the error message that you are receiving?

    Gary

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Sep 2008
    Location
    Jacksonville, Florida
    Posts
    147

    Re: MVC1 - Invalid Values persist on form and Model

    Quote Originally Posted by gep13 View Post
    Hey,

    What is the error message that you are receiving?

    Gary
    The Model being passed in isn't updated. So the same error message, continues to the next run.
    vb.net and C# in 2008 .net 3.5
    ImaginaryDevelopment blog

  4. #4
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: MVC1 - Invalid Values persist on form and Model

    Could you clear it before the foreach loop?

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Sep 2008
    Location
    Jacksonville, Florida
    Posts
    147

    Re: MVC1 - Invalid Values persist on form and Model

    Clear the error from ModelState? that wouldn't help as I am not able to get the updated values, they don't come in on the next pass into the Controller.
    vb.net and C# in 2008 .net 3.5
    ImaginaryDevelopment blog

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width