2011-02-26 39 views
6

Problema: He creado un objeto de perfil personalizado como lo describe Joel here. Luego utilicé el método de Jeremy (here) para extender el perfil personalizado para permitirme usar generar un usuario y establecer esos valores. Luego creé un ViewModel para mostrar información de Memeberhip e información de perfil para que el usuario pueda actualizar su información de membresía (correo electrónico) e información de perfil. ** La vista muestra todos los campos de la información introducida en la información actualizada en la vista y haga clic en Guardar, donde me sale el siguiente errorPerfil Objeto + Ver Modelo + Actualizar Perfil de usuario MVC C#

System.Configuration.SettingsPropertyNotFoundException: La configuración de la propiedad 'FirstName' no ha sido encontrado. **

Esto es mi costumbre objeto de perfil (Modelo):

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Profile; 
using System.Web.Security; 


namespace NDAC.Models 
{ 
    public class ProfileInformation : ProfileBase 
    { 
     static public ProfileInformation CurrentUser 
     { 
      get 
      { 
       if (Membership.GetUser() != null) 
       { 
        return (ProfileInformation)(ProfileBase.Create(Membership.GetUser().UserName)); 
       } 
       else 
       { 
        return null; 
       } 
      } 
     } 

     public virtual string FirstName { 
      get 
      { 

       return ((string)(base["FirstName"])); 
      } 
      set 
      { 
       base["FirstName"] = value; Save(); 
      } 
     } 
     public virtual string LastName { 
      get 
      { 
       return ((string)(base["LastName"])); 
      } 
      set 
      { 
       base["LastName"] = value; Save(); 
      } 
     } 
     public string Street 
     { 
      get 
      { 
       return ((string)(base["Street"])); 
      } 
      set 
      { 
       base["Street"] = value; Save(); 
      } 
     } 
     public string Street2 
     { 
      get 
      { 
       return ((string)(base["Street2"])); 
      } 
      set 
      { 
       base["Street2"] = value; Save(); 
      } 
     } 
     public string City 
     { 
      get 
      { 
       return ((string)(base["City"])); 
      } 
      set 
      { 
       base["City"] = value; Save(); 
      } 
     } 
     public string State 
     { 
      get 
      { 
       return ((string)(base["State"])); 
      } 
      set 
      { 
       base["State"] = value; Save(); 
      } 
     } 
     public string ZipCode 
     { 
      get 
      { 
       return ((string)(base["ZipCode"])); 
      } 
      set 
      { 
       base["ZipCode"] = value; Save(); 
      } 
     } 
     public string PhoneNumber 
     { 
      get 
      { 
       return ((string)(base["PhoneNumber"])); 
      } 
      set 
      { 
       base["PhoneNumber"] = value; Save(); 
      } 
     } 
     public string SemesterID 
     { 
      get 
      { 
       return ((string)(base["SemesterID"])); 
      } 
      set 
      { 
       base["SemesterID"] = value; Save(); 
      } 
     } 

     static public ProfileInformation GetProfile(string username) 
     { 
      return Create(username) as ProfileInformation; 
     } 

     internal static ProfileInformation NewUser 
     { 
      get { return System.Web.HttpContext.Current.Profile as ProfileInformation; } 
     } 

    } 
} 

Aquí está el método GET PerfilUsuario:

[Authorize] 
     public ActionResult UserProfile() 
     { 
      string id = User.Identity.Name.ToString(); 
      MembershipUser user = Membership.GetUser(id); 

      var model = new UserViewModel(); 

      UserInformation userInf = new UserInformation(); 
      userInf.Username = user.UserName; 
      userInf.Email = user.Email; 

      ProfileInformation currentProfile = ProfileInformation.GetProfile(user.UserName); 

      model.Profile = currentProfile; 
      model.UserInf = userInf;  

      return View(model); 

     } 

Como se puede ver que estoy usando un modelo de vista para mostrar la vista. El Modelo Vista es la siguiente:

public class UserViewModel 
    { 

     public UserInformation UserInf{ get; set; } 
     public ProfileInformation Profile { get; set; } 


    } 

Y, finalmente, el método para la actualización HttpPost PerfilUsuario es:

[Authorize] 
     [HttpPost] 
     public ActionResult UserProfile(UserViewModel model) 
     { 
      ProfileInformation currentProfile = ProfileInformation.GetProfile(User.Identity.Name.ToString()); 

      ProfileInformation.CurrentUser.FirstName = model.Profile.FirstName; 
      currentProfile.LastName = model.Profile.LastName; 
      currentProfile.Street = model.Profile.Street; 
      currentProfile.Street2 = model.Profile.Street2; 
      currentProfile.City = model.Profile.City; 
      currentProfile.State= model.Profile.State; 
      currentProfile.ZipCode = model.Profile.ZipCode; 
      currentProfile.PhoneNumber = model.Profile.PhoneNumber; 
      currentProfile.Save(); 

      MembershipUser user = Membership.GetUser(User.Identity.Name.ToString()); 
      user.Email = model.UserInf.Email; 
      Membership.UpdateUser(user); 


      TempData["SuccessMessage"] = "Your Profile information has been saved"; 
      ViewBag.Title = "My Profile"; 
      return RedirectToAction("ProfileUpdated"); 
     } 

El problema es que no puedo averiguar de dónde procede el error de . El formulario muestra que ingresé información válida y luego me dicen "No se encontró la propiedad de configuración 'Nombre'." Es como si UserViewModel estuviera intentando actualizar ProfileInformation.cs (objeto de perfil personalizado) pero está diciendo que no puede encontrar el objeto ... Creo que es porque no tiene un perfil para actualizar ... pero yo no puede llegar al error antes de publicar ... ¡tan frustrante! ¡Cualquier ayuda sería muy apreciada! Gracias por tomarse el tiempo para verificar esto.

También te dejaré con mi método de Registro que utiliza el objeto personalizado Perfil éxito e incluso actualiza la propiedad a nombre de "ScoobyDoo" para propósitos de prueba :)

[HttpPost] 
     public ActionResult Register(RegisterModel model) 
     { 
      if (ModelState.IsValid) 
      { 
       // Attempt to register the user 
       MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email, model.SecretQuestion, model.SecretAnswer); 

       if (createStatus == MembershipCreateStatus.Success) 
       { 

        FormsService.SignIn(model.UserName, false /* createPersistentCookie */); 
        Roles.AddUserToRole(model.UserName, "Student"); 
        ProfileInformation.NewUser.Initialize(model.UserName, true); 
        ProfileInformation.NewUser.Save(); 

        string currentSemesterID = CurrentSemester; 
        ProfileInformation profile = ProfileInformation.GetProfile(model.UserName); 
        profile.SemesterID = currentSemesterID; 
        profile.FirstName = "ScoobyDoo"; 

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

      // If we got this far, something failed, redisplay form 
      ViewBag.PasswordLength = MembershipService.MinPasswordLength; 
      return View(model); 
     } 

Respuesta

1

Es posible que necesite para proporcionar la su implementación de perfil propio ... Si lo ha hecho, ¿ha agregado su tipo de proveedor personalizado a su "web.config"?

Ejemplo:

<profile defaultProvider="TableProfileProvider" enabled="true" inherits="YourNamespace.YourClass, YourNamespace"> 

Gran artículo de MSDN here, here y here.

¡Espero que esto lo ponga en camino!

Cuestiones relacionadas