Update database record

2019-09-19 00:35发布

I'm trying to update an existing record in a table of profiles using C# MVC.

I need to make 2 separate registration forms.

I have already done the first one and it's working as planned which creates the user record in the database with basic info.

    [HttpPost]
    public ActionResult Register(Registration signingUp)
    {
        var db = new ShareRideDBEntities();

        if (ModelState.IsValid)
        {
            var Data = db.tblProfiles.Create();

            Data.Prof_Email = signingUp.Email;
            Data.Prof_Password = signingUp.Password;
            db.tblProfiles.Add(Data);

            int Saved = db.SaveChanges();

            if (Saved != 0)
            {
                Response.Write("Success.");
            }
            else
            {
                Response.Write("Error.");
            }
        }
        if (ModelState.IsValid)
        {
            if (ValidateUser(signingUp.Email, signingUp.Password))
            {
                FormsAuthentication.SetAuthCookie(signingUp.Email, false);
                return RedirectToAction("Index", "Members");
            }
            else
            {
                ModelState.AddModelError("", "");
            }
        }
        return View();
    }

What I want to do now is add to that existing record some new info using another form.

The form is asking for his name, last name, phone number and an option (with radio buttons) if he/she is a male or female.

If you need more info please comment, I'll put it asap.

EDIT:

on my Model

public class Registration
{
    [EmailAddress]
    public string Email { get; set; }

    [DataType(DataType.Password)]
    public string Password { get; set; }
}

on my second model

public class ServiceRegistration
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
}

I still don't have a the HttpPost method done for the second registration since I am not sure how to do it.

EDIT:

Ok so I have made a few changes base on the answer I got

My ServiceRegistration.cs model

using System.Web;
using System.ComponentModel.DataAnnotations;

namespace ShareRide.Models.Service
{
    public class ServiceRegistration
    {
        [Required]
        public Guid UserID { get; set; }

        [Required(AllowEmptyStrings= false, ErrorMessage="Necesary Field.")]
        public string FirstName{ get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Necesary Field.")]
        public string LastName{ get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Necesary Field.")]
        public string Phone{ get; set; }
    }
}

on my MembersController.cs controller

public ActionResult Registrationform()
    {
        return View();
    }

    [HttpGet]
    public ActionResult Registrationform(Guid UserID)
    {
        var model = new ServiceRegistration { UserID = UserID };

            return View(model);
    }

    [HttpPost]
    public ActionResult Registrationform(ServiceRegistration model)
    {
        var db = new ShareRideDBEntities();
        if (ModelState.IsValid)
        {
            var Data = db.tblProfiles.Create();

            Data.PROF_UserID = model.UserID;
            Data.PROF_FirstName = model.Home_Address;
            Data.PROF_LastName = model.Work_Address;
            Data.PROF_Phone = model.Travel_Days;

            db.SaveChanges();

            return RedirectToAction("Index", "Members");

        }
        return View(model);
    }

Now I'm getting an error on model.UserID; Cannot implicitly convert type 'System.Guid' to 'int'

On my database PROF_UserID is the primary key and is an int.

Also I commented the Data.PROF_UserID = model.UserID; so I could build but when I try to access the Registrationform view it returns an error: View error

2条回答
等我变得足够好
2楼-- · 2019-09-19 01:23

Firstly you need to amend your ServiceRegistration model to take in your user id so we can attach it to our entity. I've also added data annotations for validation purposes but you can choose to ignore these if you like.

public class ServiceRegistration
{
    [Required]
    public int Id { get; set; }
    [Required]
    public String FirstName { get; set; }
    [Required]
    public String LastName { get; set; }
    [Required]
    public String Phone { get; set; }

}

Next you need two actions. One to serve the form from a GET request and one save the record from a POST request.

Notice how we're passing the user's id over

public ActionResult AddUserInfo(int id)
{
    var model = new ServiceRegistration{ id = id }

    return View(model);
}

Im not sure how your dbContext is finding or adding users so you will need to add this yourself

[HttpPost]
public ActionResult AddUserInfo(ServiceRegistration model)
{

    var db = new ShareRideDBEntities();

    if(ModelState.IsValid)
    {

        //Find your user in your db context using model.Id as the reference

        //Add the User Data from the model

        db.SaveChanges();

        return RedirectToAction("Index", "Controller");

    }   

    //Form isn't valid so return form will the validation errors
    return View(model);

}

And finally your view should be named AddUserInfo and should look like this

@model my.namespace.ServiceRegistration

@using(Html.BeginForm(“AddUserInfo”, “Controller”, HttpMethod.Post))
{
    <!--Hide the id from the user-->
    Html.HiddenFor(m => m.Id)

    Html.TextboxFor(m => m.FirstName)
    Html.TextboxFor(m => m.LastName)
    Html.TextboxFor(m => m.Phone)

    Html.ValidationSummary();

    <input type=“submit” value=“Save” />
}

I've just wrote this on my mac's notepad application so there maybe a couple of syntax errors, so I apologise in advance.

I hope this helps.

查看更多
倾城 Initia
3楼-- · 2019-09-19 01:25

If you redirect the user to a different view page, you need to use TempData instead of ViewBag. Here is a rough draft of code sample. You may need to modify it to fit your needs.

Model

public class Registration
{
    [EmailAddress]
    public string Email { get; set; }

    [DataType(DataType.Password)]
    public string Password { get; set; }

    public virtual ServiceRegistration ServiceRegistration { get; set; }
}

In your HTTPPOST call, add one line in the validateuser condition statement

if (ValidateUser(signingUp.Email, signingUp.Password))
    {
        FormsAuthentication.SetAuthCookie(signingUp.Email, false);
        TempData["Registration"] = signingUp;
        return RedirectToAction("Index", "Members");
    }

View

@{
    var tempRegistration = TempData["Registration"] as Registration
}

@Html.HiddenFor(model => model.Email, new { id = "email", value= tempRegistration})
查看更多
登录 后发表回答