Domanda

How to create action and views for editing user custom informations?

Authorization is based on membership created by VS with MVC 4 project.

I've added additional columns, such as FirstName etc. I needed and registration works correctly, but I don't know how to get this attributes to show in view for @Html.EditorFor and to save changes in database (table UserProfile).

Many thanks for every tip.

Created model for edition:

public class UserProfileEdit
    {
        [Required]
        [Display(Name = "First name")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last name")]
        public string LastName { get; set; }

        [Required]
        [Display(Name = "Email")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }
    }
È stato utile?

Soluzione

So you want an edit page for editing personal information of user. Additional columns are already added to UserProfile table.

First of all you need an actionmethod for edit view. Fetch the user from database and build your UserProfileEdit model.

public ActionResult Edit()
{
            string username = User.Identity.Name;

            // Fetch the userprofile
            UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.Equals(username));

            // Construct the viewmodel
            UserProfileEdit model = new UserProfileEdit();
            model.FirstName = user.FirstName;
            model.LastName = user.LastName;
            model.Email = user.Email;

            return View(model);
}

When we post the editform, we post UserProfileEdit model. We fetch the UserProfile from database again and change the posted fields.

    [HttpPost]
    public ActionResult Edit(UserProfileEdit userprofile)
    {
        if (ModelState.IsValid)
        {
            string username = User.Identity.Name;
            // Get the userprofile
            UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.Equals(username));

            // Update fields
            user.FirstName = userprofile.FirstName;
            user.LastName = userprofile.LastName;
            user.Email = userprofile.Email;

            db.Entry(user).State = EntityState.Modified;

            db.SaveChanges();

            return RedirectToAction("Index", "Home"); // or whatever
        }

        return View(userprofile);
    }

Now it's just coding in your view. Mine looks like this:

@model UserProfileEdit

@using (Html.BeginForm("Edit", "Account"))
{
    @Html.EditorFor(model => model.FirstName)
     @Html.EditorFor(model => model.LastName)
     @Html.EditorFor(model => model.Email)

    <input type="submit" value="Save" />
}

Automapper might help if you have tons of fields for your edit model. This solution edits the current logged in user but adding username as action parameter is rather trivial.

Altri suggerimenti

For adding additional properties to the UserProfile table you will need to change a series of changes in

  • UserProfile table class
  • RegisterModel class
  • RegisterView (where you will be adding input for the new field)
  • AccountController/Register action (to read the new input value and use accordingly)

1. Modify your UserProfile class

Here in this example I am adding a new field called "MobileNumber", have declared it as type string.

[Table("UserProfiles")]
public class UserProfiles
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set;}
    public string Email { get; set;}
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MobileNumber { get; set; }
}

2. Add the additional property(ies) to your RegisterModel.cs

Add the new property in your Model. In this example where we want an extra field while user registration we need to update the RegisterModel class. Add validations if need be.

public class RegisterModel
{
    [Required]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [StringLength(11, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 11)]
    [Display(Name = "Mobile No.")]
    public string MobileNumber { get; set; }

}   

3. Display additional fields on your View

Once you have update the Model you should be able to use the @Html.TextBoxFor(m => m.MobileNumber) in your view, which will bind the MobileNumber field to your 'MobileNumber' property declared in your model.

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    @Html.LabelFor(m = m.Email)
    @Html.TextBoxFor(m => m.Email)

    @Html.LabelFor(m => m.Password)
    @Html.PasswordFor(m => m.Password)

    @Html.LabelFor(m => m.FirstName)
    @Html.TextBoxFor(m => m.FirstName)

    @Html.LabelFor(m => m.LastName)
    @Html.TextBoxFor(m => m.LastName)

    @Html.LabelFor(m => m.MobileNumber)
    @Html.TextBoxFor(m => m.MobileNumber)

    <input type="submit" value="Register">
}

4. Update your Controller - (AccountController in this case)

Last step, here you just need to read the value posted to your model and pass it along the repository for saving.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            WebSecurity.CreateUserAndAccount(model.Email, model.Password,
                                             new
                                                 {
                                                     FirstName = model.FirstName,
                                                     LastName = model.LastName,
                                                     MobileNumber = model.MobileNumber
                                                 });
            WebSecurity.Login(model.Email, model.Password);
            return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

5. Get this value back from DB and into your view

Now since your RegisterModel already has this property and so does your UserProfile class, using RegisterModel class on your view, you should be able to access the new added property.

Taken from here : How to add additional fields when using Membership in ASP.NET MVC 4

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top