1

I'll keep it simple.

My controller

public ActionResult Registrationform()
{
    if (Session["UserID"] == null)
    {
        return RedirectToAction("Index", "Main");
    }
    else
    {
        return View();
    }
}


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

        Data.PROF_HomeAddr = model.Home_Address;
        Data.PROF_WorkAddr = model.Work_Address;
        db.tblProfiles.Add(Data);

        db.SaveChanges();

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

    }
    return View(model);
}

My model

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

namespace Address.Models.Address
{
    public class AddressRegistration
    {
        [Required(AllowEmptyStrings= false, ErrorMessage="Este campo es necesario.")]
        public string Home_Address { get; set; }

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

My view

@model Address.Models.Address.AddressRegistration
@using (Html.BeginForm("Registrationform", "Members", FormMethod.Post, new {id = "wizardform"})) 
{
    @Html.ValidationSummary(true, "Please fix the errors.")
    @Html.TextBoxFor(m => m.Home_Address)
    @Html.TextBoxFor(m => m.Work_Address)
    <input type="submit" value="submit" />
}

I'm trying to update a record in my database after the user has logged in his account. He can fill this form and update his address.

In my database currently those are NULL by default.

I have a primary key set to the column named PROF_UserID.

If the user tries accessing the MembersController.cs views he/she will get redirected if (Session["UserID"] == null).

I'm trying to update the record of that specific PROF_UserID which is the one logged in already by adding the home address to PROF_HomeAddress and work address to PROF_WorkAddress in the database but the method I'm using only creates a new record, not update it.

I've search for a while and I can't find any answers on how to do it in MVC 4 C# and what not.

Thanks, if you need more info please comment.

EDIT:

I've changed a bit of the code base on the answer.

Controller

[HttpPost]
public ActionResult Registrationform(AddressRegistration model)
{
    var db = new AddressDBEntities();
    if (ModelState.IsValid)
    {
        var updateData = db.tblProfiles.FirstOrDefault(r => r.PROF_UserID == model.UserID);

        if (updateData != null)
        {

            updateData.PROF_HomeAddr = model.Home_Address;
            updateData.PROF_WorkAddr = model.Work_Address;

            db.SaveChanges();

        }

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

    }
    Response.Write("Error");
    return View();
}

Model

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

namespace Address.Models.Adress
{
    public class AddressRegistration
    {
        public int UserID { get; set; }

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

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

View

@model Address.Models.Address.AddressRegistration
@using (Html.BeginForm("Registrationform", "Members", FormMethod.Post, new {id = "wizardform"})) 
{
    @Html.HiddenFor(m=> m.UserID)
    @Html.ValidationSummary(true, "check for errors.")
    @Html.TextBoxFor(m => m.Home_Address)
    @Html.TextBoxFor(m => m.Work_Address)
    @Html.ValidationMessageFor(m=>m.Work_Address)
    <input type="submit" value="submit" />
}

I've tried this but it always ends up giving me the @Html.ValidationSummary(true, "check for errors.") error and the Response.Write("Error") one.

The ModelState.IsValid in the controller is returning false for some reason.

What am I doing wrong?

If i remove the @Html.HiddenFor(m=>m.UserID) it will return with model.UserID always 0 which will not find in the database, how can I make it so it finds the UserID the current user logged in has?

My MainController has

private bool ValidateUser(string Email, string Password)
{

    bool isValid = false;

    using (var db = new AddressDBEntities())
    {
        var User = db.tblProfiles.FirstOrDefault(u => u.PROF_Email == Email);
        if (User.PROF_Password == Password)
        {
            Session["UserID"] = User.PROF_UserID;

            isValid = true;
        }
    }

    return isValid;
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Johhan Santana
  • 2,336
  • 5
  • 33
  • 61

2 Answers2

1

but the method I'm using only creates a new record, not update it.

To update a record, you need to first fetch that record from the database, update its fields and then save changes.

var updateData = db.tblProfiles.FirstOrDefault(r=> r.PROF_UserID == YourUserID);
if(updateData != null) // record found
{
    //update fields with new values. 
    updateData.PROF_HomeAddr = model.Home_Address;
    updateData.PROF_WorkAddr = model.Work_Address;
}
db.SaveChanges(); //persist changes to database
Habib
  • 219,104
  • 29
  • 407
  • 436
  • I edited the question with the updates I've made based on your answer but I still am not getting the results I want for some reason on my part that I'm not sure how to fix. – Johhan Santana Jul 10 '14 at 15:03
  • @Johhan, what is not working ? try setting a debug point see if you get some result back in after executing FirstOrDefault – Habib Jul 10 '14 at 15:06
  • I'm getting a ModelState.IsValid false so it skips the update and all that, I'm not sure what to do to the model, should I remove the require DataTags? – Johhan Santana Jul 10 '14 at 15:10
  • If i remove the `@Html.HiddenFor(m=>m.UserID)` it will return with `model.UserID` always 0 which will not find in the database, how can I make it so it finds the UserID the current user logged in has? – Johhan Santana Jul 10 '14 at 15:20
  • @Johhan, that is a different issue than. Different than updating the database. I am not too sure about MVC, may be you could ask a different question to find the currently logged on User. – Habib Jul 10 '14 at 15:53
  • @Johhan Leaving the hidden field for the UserId, try checking the ModelState.Errors collection in your post action. This will help you determine which property caused the issue during binding. Are you sure you're setting the UserId property on the model properly? – Matt M Jul 10 '14 at 16:03
  • @MattyM how do I check the `ModelState.Errors`? – Johhan Santana Jul 10 '14 at 17:29
  • @Johhan It's a collection. You can either iterate through them, or set a breakpoint and inspect the ModelState object. – Matt M Jul 10 '14 at 17:33
  • @MattyM Hi Matty, it is working now, but I have to manually input the `UserID` into the `@Html.TextBoxFor(m=> m.UserID)` in order to update the record. Is there a way I could pull this `UserID` depending on who is logged in? – Johhan Santana Jul 10 '14 at 18:25
  • Depends on how you're authentication the user as there are various ways of doing this. If you're using the Asp Identity api you could try User.Identity.GetUserId(); – heymega Jul 10 '14 at 19:29
1

You need to bind your view to a model, which you have as empty currently:

public ActionResult Registrationform()
{
    if (Session["UserID"] == null)
    {
        return RedirectToAction("Index", "Main");
    }
    else
    {
        return View();
    }
}

Instead, do something along the lines of:

public ActionResult Registrationform()
{
    if (Session["UserID"] == null)
    {
        return RedirectToAction("Index", "Main");
    }
    else
    {
        //here, use the UserID to get a reference to the user in your database and pass that to  your view:
var registration = new AddressRegistration{
     UserId = (int)Session["UserId"].ToString()
};
            return View(registration);
        }
    }

Then, your hidden field will hold the userid and in your post action, the model should be bound correctly. HOWEVER, look into using the Authorize attribute on your controller action - see here. There are better ways to control access than to do it yourself.

Hopefully, this gets you on the right track.

Community
  • 1
  • 1
Matt M
  • 3,699
  • 5
  • 48
  • 76
  • That's perfect, thank you so much. It seems so easy as well. Too bad I'm still learning all these basics, I will definitely will read about the `Authorize` attribute. Thank you! – Johhan Santana Jul 10 '14 at 20:02